Last Updated : 11 Jul, 2025
In Python, zipping is a utility where we pair one list with the other. Usually, this task is successful only in the cases when the sizes of both the lists to be zipped are of the same size. But sometimes we require that different-sized lists also be zipped. Let's discuss certain ways in which this problem can be solved if it occurs.
itertools.cycle() repeats the shorter list to match the length of the longer list. This method is efficient for situations where we want the shorter list's elements to cycle through continuously.
Python
import itertools
a= [7, 8, 4, 5, 9, 10]
b= [1, 5, 6]
# Zipping using cycle
res= list(zip(a, itertools.cycle(b)))
print(res)
[(7, 1), (8, 5), (4, 6), (5, 1), (9, 5), (10, 6)]
Explanation:
itertools.zip_longest() zips lists of different lengths by padding the shorter list with a specified value. It's useful when we need to ensure both lists are fully paired, filling missing values with a default value.
Example:
Python
import itertools
a = [7, 8, 4, 5, 9, 10]
b = [1, 5, 6]
# Zipping with zip_longest and filling with 'X'
res = list(itertools.zip_longest(a, b, fillvalue='X'))
print(res)
[(7, 1), (8, 5), (4, 6), (5, 'X'), (9, 'X'), (10, 'X')]
Explanation:
enumerate() with modulo indexing allows the shorter list to cycle through its elements as the longer list progresses. This method gives more control over how the shorter list is reused when it's exhausted.
Python
a = [7, 8, 4, 5, 9, 10]
b = [1, 5, 6]
res = []
# Loop through a with index
for i, item in enumerate(a):
# Cycle b using modulo
res.append((item, b[i % len(b)]))
print(res)
[(7, 1), (8, 5), (4, 6), (5, 1), (9, 5), (10, 6)]
Explanation:
List comprehension allows for custom logic when zipping two lists. This method provides more control, such as handling missing elements based on specific conditions.
Example:
Python
a= [7, 8, 4, 5, 9, 10]
b= [1, 5, 6]
# Pair a and b, replace falsy b values with 'X'
res = [(x, y if y else 'X') for x, y in zip(a, b)]
print(res)
[(7, 1), (8, 5), (4, 6)]
Explanation:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4