I've read that yield
is a generator but I can't really see what it implies since the output of the following function is exactly the same:
def yieldFunction(number):
for x in range(number) :
yield x*2
def returnFunction(number):
output=[]
for x in range(number) :
output.append(x*2)
return output
for x in yieldFunction(10):
print(x)
print('-'*20)
for x in returnFunction(10):
print(x)
Output:
0 2 4 6 8 10 12 14 16 18
0 2 4 6 8 10 12 14 16 18
In which case one is preferred over the other?
yield
you use less memory - try to run second example with very big value and will use a lot of memory. Andyield
doesn't have to wait for full list which may need some time.while True:
inyieldFunction
you can create endless generator - and you can still use it in loop or usingit = yieldFunction(), value = next(it)
. Usingwhile True:
inreturnFunction
it will never end functionreturnFunction
and program will hang.