Code Explanation:
1. Generator Function Definition
def f():
for i in range(3):
yield i
def f():
Defines a generator function named f.
for i in range(3):
Loops over the values 0, 1, 2.
yield i
Yields the current value of i.
This makes f() a generator, which returns an iterator when called.
2. Creating a Generator Object
g = f()
Calls the generator function f() and assigns the returned generator object to variable g.
3. Advancing the Generator Once
next(g)
Advances the generator g by one step.
i = 0 is yielded. So the generator is now paused at i = 1.
Note: This value is discarded (not printed or stored).
4. Reassigning the Generator Object
g = f()
A new generator object is created and assigned to g.
The previous generator (which had already yielded one value) is discarded.
This new g starts fresh from i = 0.
5. Converting the Generator to a List
print(list(g))
list(g) consumes the new generator fully.
It collects all yielded values: [0, 1, 2]
Output:
[0, 1, 2]
Final Output
[0, 1, 2]
Download Book - 500 Days Python Coding Challenges with Explanation
.png)

0 Comments:
Post a Comment