Q:

Python | Convert Tuple to Tuple Pair

belongs to collection: Python Tuple Programs

0

Example:

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

Converting Tuple to Tuple Pair

To perform the task of converting tuples to tuple pairs, we will be traversing the tuple and making pairs of the sets of two elements. Python programming language provides programmers with multiple methods 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 by making pairs elements of the tuple using the product() method and then using the next() method to select the next element from the tuple.

# Program to convert Tuple to Tuple 
# Pair in Python

from itertools import product

# Creating tuple and print its values
myTuple = ('x', 'y', 'z')
print("Tuple of three elements : " + str(myTuple))

# Converting tuple to tuple pairs 
myTuple = iter(myTuple)
pairTupleList = list(product(next(myTuple), myTuple))

# printing result
print("Lists with tuple pairs are : " + str(pairTupleList))

Output:

Tuple of three elements : ('x', 'y', 'z')
Lists with tuple pairs are : [('x', 'y'), ('x', 'z')]

Method 2:

Another method to solve the problem is by using repeating elements of the tuple using the repeat() method along with next() method. Then we will be zipping the created pair tuples into a list using zip() and list methods.

# Program to convert Tuple to Tuple 
# Pair in Python

from itertools import repeat

# Creating tuple and print its values
myTuple = ('x', 'y', 'z')
print("Tuple of three elements : " + str(myTuple))

# Converting tuple to tuple pairs 
myTuple = iter(myTuple)
pairTupleList = list(zip(repeat(next(myTuple)), myTuple))

# printing result
print("Lists with tuple pairs are : " + str(pairTupleList))

Output:

Tuple of three elements : ('x', 'y', 'z')
Lists with tuple pairs are : [('x', 'y'), ('x', 'z')]

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 program to sort tuples by total digits... >>
<< Python program to alternate elements operation on ...