![]() |
VOOZH | about |
In Python, zipping is a utility where we pair one record with the other. Usually, this task is successful only in cases when the sizes of both the records to be zipped are of the same size. But sometimes we require that different-sized records also be zipped. Let’s discuss certain ways in which this problem can be solved if it occurs.
Method #1 : Using enumerate() + loop
This is the way in which we use the brute force method to achieve this particular task. In this process, we loop both the tuple and when one becomes larger than the other we cycle the elements to begin them from the beginning.
The original tuple 1 is : (7, 8, 4, 5, 9, 10) The original tuple 2 is : (1, 5, 6) The zipped tuple is : [(7, 1), (8, 5), (4, 6), (5, 1), (9, 5), (10, 6)]
Method #2: Using itertools.cycle()
This is yet another way to perform this particular task, in this we cycle the smaller tuple so that it can begin zipping from the beginning in case the smaller tuple gets exhausted using a zip function.
The original tuple 1 is : (7, 8, 4, 5, 9, 10) The original tuple 2 is : (1, 5, 6) The zipped tuple is : [(7, 1), (8, 5), (4, 6), (5, 1), (9, 5), (10, 6)]
Method 3: List comprehension with a ternary operator
The original tuple 1 is : (7, 8, 4, 5, 9, 10) The original tuple 2 is : (1, 5, 6) The zipped tuple is : [(7, 1), (8, 5), (4, 6), (5, 1), (9, 5), (10, 6)]
Time complexity: O(n), where n is the length of the larger tuple.
Auxiliary Space: O(n), as we're creating a new list to store the zipped tuple.
Method # 4 : Using numpy module
OUTPUT : The zipped tuple is : ((7, 1), (8, 5), (4, 6), (5, 1), (9, 5), (10, 6))
Time complexity: O(n)
Auxiliary Space: O(n)