Why are these 2 generators different? | Sololearn: Learn to code for FREE!
+ 1

Why are these 2 generators different?

https://code.sololearn.com/ch307I4u0iKi/?ref=app gen1 and gen2() are both generators and you could use them in a loop the same way, but... If you use next() several times you won't get the same result : gen2() seems to rewind every time you call next() while gen1 will successively display the expected values as in a loop. Besides you can use gen1 only once while you can use gen2() as many times as you want. Why is that? Is there a way to get the successive values of gen2 using next()?

5th Jun 2019, 5:32 AM
Jean-François Harvier
Jean-François Harvier - avatar
2 ответов
+ 5
They are both generators, but you're calling them in a different way. gen1 = (x for x in range(3)) creates a generator object and with next(gen1) you're getting the next item from the same generator object until the generator is exhausted. next(gen2()) will create a new generator object each time you call it, so with each call it will start over again. To get the same result as with gen1(), create a generator object first and then call next() on that object, not on the function: x = gen2() print(next(x)) # 0 print(next(x)) # 1 etc.
5th Jun 2019, 5:49 AM
Anna
Anna - avatar
+ 1
Thank you for your answer Anna! I think I get it now : gen2 is a function which creates a generator when called. It all makes sense.
5th Jun 2019, 6:05 AM
Jean-François Harvier
Jean-François Harvier - avatar