Python Programming - Generators - Discussion

Discussion Forum : Generators - General Questions (Q.No. 88)
88.
How does the itertools.zip_longest() function differ from zip() when used with generators?
They are equivalent in functionality
itertools.zip_longest() stops when the longest iterable is exhausted, while zip() stops when the shortest iterable is exhausted
zip() raises a ValueError when used with generators
itertools.zip_longest() raises a StopIteration exception when used with generators
Answer: Option
Explanation:
itertools.zip_longest() continues until the longest iterable is exhausted, filling in missing values with a specified fillvalue. zip() stops when the shortest iterable is exhausted.
import itertools

gen1 = (1, 2, 3)
gen2 = ('a', 'b')

zipped_iterable = itertools.zip_longest(gen1, gen2, fillvalue=None)
regular_zip = zip(gen1, gen2)

print(list(zipped_iterable))    # Output: [(1, 'a'), (2, 'b'), (3, None)]
print(list(regular_zip))         # Output: [(1, 'a'), (2, 'b')]
Discussion:
Be the first person to comment on this question !

Post your comments here:

Your comments will be displayed after verification.