Code Explanation:
1. Defining the inner Generator Function
def inner():
yield 1
yield 2
inner() is a generator function, which means it returns an iterator when called.
It yields:
First: 1
Then: 2
2. Defining the outer Generator Function
def outer():
yield from inner()
outer() is also a generator.
yield from inner() delegates to the inner() generator.
It automatically yields all values from inner(), one by one.
So outer() behaves just like inner() here.
3. Calling and Converting to a List
print(list(outer()))
outer() is called, returning a generator.
list(...) consumes the generator, collecting all yielded values into a list.
Output:
[1, 2]
4. Why yield from is Useful
It’s a cleaner, more readable way to re-yield values from a sub-generator.
Without yield from, you’d have to do:
def outer():
for value in inner():
yield value
Final Output
[1, 2]
0 Comments:
Post a Comment