Skip to content

Python zip different length

  • by

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:

Python zip different length

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’)]

Do 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.

Leave a Reply

Your email address will not be published. Required fields are marked *