6

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?

Sebastien D
  • 4,369
  • 4
  • 18
  • 46
  • Go through https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do – Venfah Nazir May 23 '19 at 08:37
  • 1
    with `yield` you use less memory - try to run second example with very big value and will use a lot of memory. And `yield` doesn't have to wait for full list which may need some time. – furas May 23 '19 at 08:43
  • Thanks, very illustrative suggestion, just tried it and could see the result – Sebastien D May 23 '19 at 08:46
  • 1
    using `while True:` in `yieldFunction` you can create endless generator - and you can still use it in loop or using `it = yieldFunction(), value = next(it)`. Using `while True:` in `returnFunction` it will never end function `returnFunction` and program will hang. – furas May 23 '19 at 08:53

0 Answers0