Code Explanation:
๐น 1. Generator Function Definition
def gen():
✅ Explanation:
A function named gen() is created.
Since it contains yield, it becomes a generator function.
Calling it will return a generator object.
๐น 2. First yield
yield 1
✅ Explanation:
Generator produces the value:
1
Then pauses execution.
๐น 3. yield from
yield from [2, 3]
✅ Explanation:
yield from is a shortcut for yielding all values from another iterable.
Python internally treats it like:
for x in [2, 3]:
yield x
๐ First value from list
2
is yielded.
Generator pauses.
๐ Second value from list
3
is yielded.
Generator pauses again.
๐น 4. Final yield
yield 4
✅ Explanation:
After yield from finishes,
generator yields:
4
๐น 5. Calling Generator
gen()
✅ Explanation:
Does NOT execute immediately.
Creates a generator object.
Something like:
<generator object gen at 0x...>
๐น 6. Converting to List
print(list(gen()))
✅ Explanation:
list() consumes the entire generator.
It collects every yielded value.
Values generated in order:
First:
yield 1
Output:
1
Second:
yield from [2,3]
Outputs:
2
3
Third:
yield 4
Output:
4
๐น 7. Final List
Collected values:
[1, 2, 3, 4]
๐ฏ Final Output
[1, 2, 3, 4]

0 Comments:
Post a Comment