Note
Python - zip_longest() - Combine iterables and fill missing values
Overview of the Python zip_longest() function. Combine elements from several iterables (and fill missing values from shorter ones).
zip_longest(iterable_1, iterable_2, ..., fillvalue=None) returns lazy iterator that contains tuples with combined elements one by one from each iterable. zip_longest needs to be imported from itertools.
It's biggest difference from "standard" zip() is that it won't stop upon exhausting shortest iterable.
zip_longest() continues to generate tuples until the longest iterable is exhausted, filling missing values with a specified fillvalue.
As mentioned above, you can provide optional fillvalue key-word argument to let zip_longest() know with what it should replace missing values.
from itertools import zip_longest
my_list_1 = [1, 2, 3, 4, 5]
my_string_1 = "curiosity"
my_zip = zip_longest(my_list_1, my_string_1)
for element in my_zip:
print(element)
Output:
(1, 'c')
(2, 'u')
(3, 'r')
(4, 'i')
(5, 'o')
(None, 's')
(None, 'i')
(None, 't')
(None, 'y')
Please notice that order of iterables is preserved.
Using zip_longest() with multiple iterables and fillvalue
zip_longest() can also accept more arguments and it accepts optional argument fillvalue:
from itertools import zip_longest
my_list_1 = [1, 2, 3, 4, 5]
my_string_1 = "curiosity"
my_range = range(0, 3)
another_zip = zip_longest(my_list_1, my_string_1, my_range, fillvalue="Empty")
for element in another_zip:
print(element)
Output:
(1, 'c', 0)
(2, 'u', 1)
(3, 'r', 2)
(4, 'i', 'Empty')
(5, 'o', 'Empty')
('Empty', 's', 'Empty')
('Empty', 'i', 'Empty')
('Empty', 't', 'Empty')
('Empty', 'y', 'Empty')
Please notice that zip_longest() don't stop on shortest iterable but continue while adding None or provided fillvalue.
Key Points to Remember about zip_longest()
-
Lazy Evaluation:
zip_longest()returns an iterator, which means tuples are generated only when needed, making it memory-efficient for large datasets. -
Longest Iterable: Unlike
zip(),zip_longest()continues until the longest iterable is exhausted, filling missing values from shorter iterables. -
Custom Fill Values: Use the
fillvalueargument to specify a custom value for missing elements. If not provided it defaults toNone.
I hope you found this helpful! If you have any feedback, questions or requests, please reach out to me through Contact page!