Python generators | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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?

24th Sep 2020, 9:19 AM
M Tamim
M Tamim - avatar
4 Answers
+ 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.
24th Sep 2020, 9:32 AM
HonFu
HonFu - avatar
+ 4
Oh no!! 😫 HonFu, Thanks, anyway 😍
24th Sep 2020, 9:58 AM
M Tamim
M Tamim - avatar
+ 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.
24th Sep 2020, 10:04 AM
HonFu
HonFu - avatar
+ 2
HonFu, ya, did so.. 😊
24th Sep 2020, 10:23 AM
M Tamim
M Tamim - avatar