Python zip different lengths by equaling the length of the shortest input list. But the built-in zip
won’t repeat to pair with the list with a larger size list.
Python zip different length
Simple example code zip two differently sized lists, repeating the shorter list? The iterator will stop when it reaches the third element. Therefore, we have three tuples in the output tuple.
A = [1, 2, 3, 4, 5, 6, 7, 8, 9]
B = ["A", "B", "C"]
res = zip(A, B)
print(list(res))
Output:
Repeats indefinitely
A = [1, 2, 3, 4, 5, 6, 7, 8, 9]
B = ["A", "B", "C"]
from itertools import cycle
res = zip(A, cycle(B)) if len(A) > len(B) else zip(cycle(A), B)
print(list(res))
Output:
[(1, ‘A’), (2, ‘B’), (3, ‘C’), (4, ‘A’), (5, ‘B’), (6, ‘C’), (7, ‘A’), (8, ‘B’), (9, ‘C’)]
If you want to zip iterables of different lengths and fill the missing values with a specific value (like None
), you can use itertools.zip_longest
:
from itertools import zip_longest
list1 = [1, 2, 3]
list2 = ['a', 'b']
list3 = [True, False, True, False]
zipped = list(zip_longest(list1, list2, list3, fillvalue=None))
print(zipped)
In this case, zipped
will be [(1, 'a', True), (2, 'b', False), (3, None, True), (None, None, False)]
.
Comment if you have any doubts or suggestions on this Python zip function.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.