+ 1

A question from duels. Why the second cycle "for" is not working? I don't know what to search for.

def Count_to_5(): for i in range(1,6): yield(i) a = Count_to_5() n = 0 for i in a: n += 1 print(n) for i in a: {why this is not working?} n -= 1 print(n) >>5 >>5

10th Aug 2018, 5:38 AM
Greenman
2 Réponses
+ 17
Generators are iterators, a kind of iterable you can only iterate over once. Generators do not store all the values in memory, they generate the values on the fly... 🕊️🦋🦅 so after using a in 1st for loop... it's value becomes [] empty... so 2nd for loop is not executed... so value of n remains the same 5
10th Aug 2018, 8:17 AM
🌛DT🌜
🌛DT🌜 - avatar
0
thank you for answering. So much to learn here.
11th Aug 2018, 2:00 PM
Greenman