Python – Convert Tuple to Tuple Pair

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().

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


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().

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output :

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



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.