Because generator return
statements don't return anything, they end the execution (python knows this is a generator because it contains at least one yield
statement). Instead of return [n]
do
yield n
return
EDIT
after raising this with the python core devs, they pointed me to the python docs where it says
In a generator function, the return statement indicates that the generator is done and will cause StopIteration to be raised. The returned value (if any) is used as an argument to construct StopIteration and becomes the StopIteration.value attribute.
So you can do
def f(n):
if n < 2:
return [n]
for i in range(n):
yield i * 2
g = f(1)
res = []
while True:
try:
res.append(next(g))
except StopIteration as e:
if e.value is not None:
res = e.value
break
if you really, really wanted.