Python Programming - Generators - Discussion

Discussion Forum : Generators - General Questions (Q.No. 64)
64.
How does the itertools.zip_longest() function differ from zip() when used with generators?
They are equivalent in functionality
itertools.zip_longest() fills in missing values with None, while zip() stops when the shortest iterable is exhausted
zip() fills in missing values with None, while itertools.zip_longest() stops when the shortest iterable is exhausted
itertools.zip_longest() raises a ValueError if iterables are of different lengths
Answer: Option
Explanation:
itertools.zip_longest() fills in missing values with None for the shorter iterables, while zip() stops when the shortest iterable is exhausted.
import itertools

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

zipped = zip(gen1, gen2)
zip_longest = itertools.zip_longest(gen1, gen2)

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

Post your comments here:

Your comments will be displayed after verification.