Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Zip Uneven Tuple in Python
In Python, when working with tuples of different lengths, the standard zip() function stops at the shortest tuple. However, there are several methods to zip uneven tuples where all elements from the longer tuple are preserved by cycling through the shorter one.
What is Zipping of Uneven Tuples?
Zipping combines elements from multiple tuples into pairs. For example:
# Standard zip stops at shortest tuple
t1 = (1, 2, 3, 4)
t2 = ("a", "b")
result = list(zip(t1, t2))
print("Standard zip result:", result)
Standard zip result: [(1, 'a'), (2, 'b')]
With uneven tuple zipping, we cycle through the shorter tuple to match the longer one's length ?
Using For Loop and Enumerate
This method uses the modulo operator to cycle through the shorter tuple ?
# Using for loop and enumerate
tup1 = (7, 8, 4, 5)
tup2 = (1, 5, 6)
print("Input tuple 1:", tup1)
print("Input tuple 2:", tup2)
result = []
for i, element in enumerate(tup1):
result.append((element, tup2[i % len(tup2)]))
print("Zipped result:", result)
Input tuple 1: (7, 8, 4, 5) Input tuple 2: (1, 5, 6) Zipped result: [(7, 1), (8, 5), (4, 6), (5, 1)]
Using List Comprehension
This approach handles both cases where either tuple can be longer ?
# Using list comprehension with conditional logic
tup1 = (7, 8, 4, 5)
tup2 = (1, 5, 6)
print("Input tuple 1:", tup1)
print("Input tuple 2:", tup2)
result = [(tup1[i % len(tup1)], tup2[i % len(tup2)])
for i in range(max(len(tup1), len(tup2)))]
print("Zipped result:", result)
Input tuple 1: (7, 8, 4, 5) Input tuple 2: (1, 5, 6) Zipped result: [(7, 1), (8, 5), (4, 6), (5, 1)]
Using itertools.cycle
The itertools.cycle function provides an elegant solution ?
import itertools
tup1 = (7, 8, 4, 5)
tup2 = (1, 5, 6)
print("Input tuple 1:", tup1)
print("Input tuple 2:", tup2)
# Determine which tuple is longer
if len(tup1) >= len(tup2):
result = list(zip(tup1, itertools.cycle(tup2)))
else:
result = list(zip(itertools.cycle(tup1), tup2))
print("Zipped result:", result)
Input tuple 1: (7, 8, 4, 5) Input tuple 2: (1, 5, 6) Zipped result: [(7, 1), (8, 5), (4, 6), (5, 1)]
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| For Loop + Enumerate | Good | Fast | Simple cases |
| List Comprehension | Moderate | Fast | One-liners |
| itertools.cycle | Excellent | Very Fast | Professional code |
Conclusion
Use itertools.cycle for the most readable and efficient solution. The modulo operator approach works well for simple cases, while list comprehension offers a concise one-liner solution.
