Code Explanation:
1. Function Definition
def nums():
for i in range(5):
yield i
def nums(): defines a generator function named nums.
Inside it, for i in range(5): loops over values 0 to 4.
yield i pauses the function and yields a value (instead of returning), allowing the function to resume from that point on the next call.
This generator will produce values: 0, 1, 2, 3, 4, one at a time when iterated.
2. Creating the Generator
g = nums()
Calls the nums() function and stores the generator object in variable g.
No values are produced yet—g is just a generator ready to be used.
3. First Iteration with Break
for n in g:
if n == 2:
break
Starts iterating through g.
First iteration: n = 0 → not 2 → loop continues.
Second iteration: n = 1 → not 2 → loop continues.
Third iteration: n = 2 → matches condition → break exits the loop.
At this point, the generator g has already yielded 0, 1, and 2 and is currently paused after 2. But because of break, iteration stops and generator is not reset.
4. Second Iteration with list(g)
print(list(g))
Now we convert the remaining values in the generator g into a list.
Since the generator was paused after yielding 2, it resumes from i = 3.
So it yields 3 and 4.
The generator is then exhausted.
The result is: [3, 4]
Final Output
[3, 4]
Download Book - 500 Days Python Coding Challenges with Explanation
.png)

0 Comments:
Post a Comment