Code Explanation:
1. Define sub() – A Generator Function
def sub():
yield from [1, 2]
This function is a generator.
yield from [1, 2] yields the values 1 and 2, one by one.
So calling sub() will yield:
1, then 2.
2. Define main() – Another Generator Function
def main():
yield 0
yield from sub()
yield 3
This generator yields values in three steps:
yield 0
→ First value it yields is 0.
yield from sub()
→ Calls the sub() generator, which yields:
1, then 2.
yield 3
→ Finally, yields 3.
So calling main() yields:
0, 1, 2, 3
3. Print the Generator as a List
print(list(main()))
Converts the generator into a list by consuming all its values.
Final result:
[0, 1, 2, 3]
Final Output
[0, 1, 2, 3]
Download Book - 500 Days Python Coding Challenges with Explanation
.png)

0 Comments:
Post a Comment