Code Explanation:
๐น 1. Generator Function Definition
def gen():
for i in range(3):
yield i
✅ Explanation:
gen() is a generator function because it uses yield.
It produces values one by one instead of returning all at once.
๐ What it will generate:
0 → 1 → 2
๐น 2. Creating Generator Object
g = gen()
✅ Explanation:
Calling gen() does NOT run the function immediately.
It returns a generator object.
Execution starts only when iterated (next() or loop).
๐น 3. Iterating Using for Loop
for x in g:
print(x)
๐ What happens internally:
Python repeatedly calls:
next(g)
Step-by-step execution:
yield 0 → prints 0
yield 1 → prints 1
yield 2 → prints 2
Generator is exhausted → loop stops
✔️ Output so far:
0
1
2
๐น 4. Converting Generator to List
print(list(g))
๐จ Important:
Generator g is already exhausted after the loop
No values left to produce
๐ So:
list(g) → []
๐ฏ Final Output
0
1
2
[]

0 Comments:
Post a Comment