Explanation:
1. Creating the Generator
g = (x for x in range(10) if x % 2 == 0)
This is a generator expression.
range(10) gives:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
The condition:
x % 2 == 0
keeps only the even numbers.
So the generator will produce:
0, 2, 4, 6, 8
⚠️ Important: A generator does not create the complete list immediately. It produces values one at a time when requested.
2. First next(g)
next(g)
The first value generated is:
0
So:
next(g) → 0
3. Second next(g)
next(g)
The generator continues from where it stopped.
The next even number is:
2
So:
next(g) → 2
4. Third next(g)
Again, the generator continues forward.
The next value is:
4
So:
next(g) → 4
5. Adding the Values
Now the expression becomes:
0 + 2 + 4
Therefore:
6
6. print() Statement
print(next(g) + next(g) + next(g))
prints:
6
✅ Final Output
6

0 Comments:
Post a Comment