+ 1

Someone please explain this problem

def count_to_5(): for i in range(1,6): yield(i) c = count_to_5() n = 0 for i in c: n += 1 for i in c: n -= 1 print(n) #Output: 5 #Why and how output is 5?

25th Sep 2021, 5:03 AM
Ferdous ☑
Ferdous ☑ - avatar
1 Answer
+ 5
A generator will no longer yield once it had completed generating. So your second attempt to read from it (where you decremented <n> by 1) is of no effect, and <n> will still have 5 as its value. To verify this, add print( n ) underneath the line decrementing <n> in the second for...in loop.
25th Sep 2021, 5:18 AM
Ipang