Code Explanation:
1. Define gen1() – A Generator Function
def gen1():
yield from [1, 2, 3]
This defines a generator function named gen1.
yield from [1, 2, 3] means: yield each value from the list [1, 2, 3] one by one.
So when you call gen1(), it will yield:
1, then 2, then 3.
2. Define gen2() – Another Generator Function
def gen2():
yield from ['a', 'b', 'c']
Similar to gen1, but now yielding strings from the list ['a', 'b', 'c'].
When called, gen2() will yield:
'a', 'b', 'c'.
3. Use zip() to Pair Elements from Both Generators
zipped = zip(gen1(), gen2())
zip() takes two or more iterables and combines them element-wise into tuples.
In this case:
From gen1(): yields 1, 2, 3
From gen2(): yields 'a', 'b', 'c'
zip pairs them:
(1, 'a')
(2, 'b')
(3, 'c')
4. Convert to List and Print
print(list(zipped))
list(zipped) consumes the zipped iterator and builds a list of tuples.
Output will be:
[(1, 'a'), (2, 'b'), (3, 'c')]
Final Output
[(1, 'a'), (2, 'b'), (3, 'c')]
Download Book - 500 Days Python Coding Challenges with Explanation
.png)

0 Comments:
Post a Comment