Q:

Python | Zip Uneven Tuple

belongs to collection: Python Tuple Programs

0

Example:

tuple = ("python", "includehelp", 43, 54.23)

Performing the operation to Zip uneven tuples

For performing zip operation on uneven tuples, we need to use elements of the smaller tuple again to zip all the elements of the larger one.

In python, this task can be performed in multiple ways giving the programmer an option to use a method based on the program’s requirement. So, let's see ways to perform the task.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Method 1:

One method to solve the problem is directly by looping over the smaller tuple and multiple times to match them with the elements of the larger tuple.

# Python program to Zip Uneven Tuples

# Creating and printing both the tuples 
tup1 = (5, 1, 7, 9, 2, 0)
tup2 = (3, 4, 6, 8)
print("The value tuples are : ")
print("tuple 1 : " + str(tup1))
print("tuple 2 : " + str(tup2))

# Performing uneven tuples Zip 
# using loops and enumerate
zipedTup = []
for i, j in enumerate(tup1):
	zipedTup.append((j, tup2[i % len(tup2)]))

# printing zipped tuple
print ("The zipped tuple is : " + str(zipedTup))

Output:

he value tuples are : 
tuple 1 : (5, 1, 7, 9, 2, 0)
tuple 2 : (3, 4, 6, 8)
The zipped tuple is : [(5, 3), (1, 4), (7, 6), (9, 8), (2, 3), (0, 4)]

Method 2:

Another approach to solve the problem is by using the cycle method to cycle through the elements of the smaller tuple elements to pair them with all elements of the larger tuple. The cycle() method is present in the itertools library of the python programming language.

# Python program to Zip Uneven Tuples

# importing cycle method from itertools library 
from itertools import cycle

# Creating and printing both the tuples 
tup1 = (5, 1, 7, 9, 2, 0)
tup2 = (3, 4, 6, 8)
print("The value tuples are : ")
print("tuple 1 : " + str(tup1))
print("tuple 2 : " + str(tup2))

# Performing uneven tuples Zip using loops and enumerate
zipedTup = list(zip(tup1, cycle(tup2)) if len(tup1) > len(tup2) else zip(cycle(tup1), tup2))

# printing zipped tuple
print ("The zipped tuple is : " + str(zipedTup))

Output:

The value tuples are : 
tuple 1 : (5, 1, 7, 9, 2, 0)
tuple 2 : (3, 4, 6, 8)
The zipped tuple is : [(5, 3), (1, 4), (7, 6), (9, 8), (2, 3), (0, 4)]

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python | Tuple elements inversions... >>
<< Python | Sum of tuple elements...