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?

4
  • Go through stackoverflow.com/questions/231767/… Commented May 23, 2019 at 8: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
    Commented May 23, 2019 at 8:43
  • Thanks, very illustrative suggestion, just tried it and could see the result Commented May 23, 2019 at 8: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
    Commented May 23, 2019 at 8:53

0

Browse other questions tagged or ask your own question.