Python - Completely unexpected | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Python - Completely unexpected

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

23rd Feb 2020, 5:32 AM
Paolo De Nictolis
Paolo De Nictolis - avatar
5 Answers
+ 11
The created generator object c can only used once. If you consume it by iterating, it is not possible to repeat this output. If you like to output it again, it has to be generated again. So after the first iteration of the generator, n = 5. The following (second) iteration will not execute because of the reason i mentioned. So the output of n is still 5.
23rd Feb 2020, 7:11 AM
Lothar
Lothar - avatar
+ 4
Now continuing the above case, for c = list(count_to_5()) Both the loops are executed normally and even after the loops the list stored in variable c does not change. So the value of n first increase and then decrease hence reaching 0 once again. I am writing this answer based on what I observed after putting print() statements in there. I hope any other user with sufficient knowledge will tell the right answer very soon!
23rd Feb 2020, 6:35 AM
Utkarsh Sharma
Utkarsh Sharma - avatar
+ 4
Lothar Thanks for the answer!
23rd Feb 2020, 7:15 AM
Utkarsh Sharma
Utkarsh Sharma - avatar
+ 4
Just a few element to add... In Python, a for loop stops when the 'StopIteration' exception is raised. When a generator has reached his end, it raises a StopIteration exception, so that the loop will break. But remember that a generator function is unique and can be used only once per instance.
23rd Feb 2020, 8:11 AM
Théophile
Théophile - avatar
+ 3
That's a nice question, I would like an answer to that too! But I put some print statements in there and saw a pattern. when you are assigning c = count_to_5() and put print(c) after that it will show the function id (I don't know if that's even a thing or not) but if you assign c = list(count_to_5()) You can see a list of 5 numbers. Now the question is why the output is 5 So let's take the first case where c = count_to_5() Here the first loop will execute 5 times as if there was actually a list of 5 numbers. For every value that function yields, loop is executed. But, I think, we have not given list() so these values are not stored anywhere. If you put print(list(c)) before the first and after the first loop, you can see, before the first loop it prints 5 values but after the first loop it prints amd empty list. Since the list is empty the second loop is never executed and the n will remain 5. Hence the output 5. But the story is a bit different for the second case. (I have reached word limit!
23rd Feb 2020, 6:26 AM
Utkarsh Sharma
Utkarsh Sharma - avatar