+ 3
Python generators
def count_to_5(): for i in range(1,6): yield i c = count_to_5() n = 0 for i in c: n += 1 print(n) for i in c: n -= 1 print(n) here, I thought the the output would be - 5 0 but it is - 5 5 why? can you explain, guys?
4 Réponses
+ 7
Generators become exhausted when the bottom of the function is reached.
A for loop calls 'next' on your generator.
The second loop runs, but since the generator c is already 'empty', it stops rightaway and no subtraction is executed.
+ 4
Oh no!! 😫
HonFu, Thanks, anyway 😍
+ 3
You can make a new generator anytime!
For example if in the second loop you write...
for i in count_to_5():
...
... you create a new generator and get the result you expect.
+ 2
HonFu, ya, did so.. 😊