I tried to create a simple Python function where the result is generator or normal output depending on a condition. But the function did not work. it seems the presence of the keyword 'yield' in the function leads the function to return a generator in all cases.
Below is a simple function that demonstrate what I tried to do.
# Generator function
def square_gen(numbers):
if len(numbers) > 3:
for number in numbers:
yield number**2
else:
output= []
for number in numbers:
output.append(number**2)
return output
The plan is to call the function in two different ways and get different corresponding outputs:
square_gen([1,2,3])
returns a generator object that I can iterate over (since length of the argument is not greater than 3) .square_gen([1,2,3,4])
returns[1,4,9,16]
(since length of the argument is greater than 3).
However, only 1)
works. It returns a generator object that one can iterate over. Surprisingly, 2)
still returns a generator object (I wonder why) but looping over this generator object results in an error.
So basically, I want to know why the non-generator branch of the function still returns a generator object.