Let’s carefully break this down.
Code:
Step 1: Generator Expression
g = (i*i for i in range(3))-
This creates a generator object.
-
It will not calculate squares immediately, but will produce values one at a time when asked (lazy evaluation).
range(3) → [0, 1, 2].
-
So generator will yield:
-
First call → 0*0 = 0
-
Second call → 1*1 = 1
-
Third call → 2*2 = 4
-
Step 2: First next(g)
-
Asks the generator for its first value.
i = 0 → 0*0 = 0.
-
Output: 0.
Step 3: Second next(g)
-
Generator resumes where it left off.
i = 1 → 1*1 = 1.
-
Output: 1.
Final Output:
⚡ If you call next(g) one more time → you’ll get 4.
⚠️ If you call again after that → StopIteration error, since generator is exhausted.


0 Comments:
Post a Comment