I have the following Python code using yield:
def foo(arg):
if arg:
yield -1
else:
return range(5)
Specifically, the foo() method shall iterate over a single value (-1) if its argument is True and otherwise iterate over range(). But it doesn't:
>>> list(range(5))
[0, 1, 2, 3, 4]
>>> list(foo(True))
[-1]
>>> list(foo(False))
[]
For the last line, I would expect the same result as for the first line ([0, 1, 2, 3, 4]). Why is this not the case, and how should I change the code so that it works?
returnwithin generator functions unless you want to prematurely stop iteration.returnterminates the function and prevents further execution. you can use forelsepart:for num in range(5): yield numyield fromis for.