Skip to content
Related Articles

Related Articles

Python – Convert Tuple to Tuple Pair

View Discussion
Improve Article
Save Article
  • Last Updated : 08 Jun, 2020

Sometimes, while working with Python Tuple records, we can have a problem in which we need to convert Single tuple with 3 elements to pair of dual tuple. This is quite a peculiar problem but can have problem in day-day programming and competitive programming. Let’s discuss certain ways in which this task can be performed.

Input : test_tuple = (‘A’, ‘B’, ‘C’)
Output : [(‘A’, ‘B’), (‘A’, ‘C’)]

Input : test_tuple = (‘X’, ‘Y’, ‘Z’)
Output : [(‘X’, ‘Y’), (‘X’, ‘Z’)]

Method #1 : Using product() + next()
The combination of above functions can be used to solve this problem. In this, we make pairs using product, the selection of pairing with next element is done using nex().




# Python3 code to demonstrate working of 
# Convert Tuple to Tuple Pair
# Using product() + next()
from itertools import product
  
# initializing tuple
test_tuple = ('G', 'F', 'G')
  
# printing original tuple
print("The original tuple : " + str(test_tuple))
  
# Convert Tuple to Tuple Pair
# Using product() + next()
test_tuple = iter(test_tuple)
res = list(product(next(test_tuple), test_tuple))
  
# printing result 
print("The paired records : " + str(res))

Output :

The original tuple : ('G', 'F', 'G')
The paired records : [('G', 'F'), ('G', 'G')]

 

Method #2 : Using repeat() + zip() + next()
This problem can also be solved using the combination of above functions. In this we perform the task of pairing using zip() and repetition using repeat().




# Python3 code to demonstrate working of 
# Convert Tuple to Tuple Pair
# Using repeat() + zip() + next()
from itertools import repeat
  
# initializing tuple
test_tuple = ('G', 'F', 'G')
  
# printing original tuple
print("The original tuple : " + str(test_tuple))
  
# Convert Tuple to Tuple Pair
# Using repeat() + zip() + next()
test_tuple = iter(test_tuple)
res = list(zip(repeat(next(test_tuple)), test_tuple))
  
# printing result 
print("The paired records : " + str(res))

Output :

The original tuple : ('G', 'F', 'G')
The paired records : [('G', 'F'), ('G', 'G')]

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!