Python | Reverse each tuple in a list of tuples

Given a list of tuples, write a Python program to reverse each tuple in the given list of tuples.

Examples:

Input : [(1, 2), (3, 4, 5), (6, 7, 8, 9)]
Output : [(2, 1), (5, 4, 3), (9, 8, 7, 6)]

Input : [('a', 'b'), ('x', 'y'), ('m', 'n')]
Output : [('b', 'a'), ('y', 'x'), ('n', 'm')]

 
Method #1 : Negative-step slicing

We can use standard negative-step slicing tup[::-1] to get the reverse of a tuple, and a list comprehension to get that for each tuple.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to Reverse 
# each tuple in a list of tuples
  
def reverseTuple(lstOfTuple):
      
    return [tup[::-1] for tup in lstOfTuple]
              
# Driver code
lstOfTuple = [(1, 2), (3, 4, 5), (6, 7, 8, 9)]
print(reverseTuple(lstOfTuple))

chevron_right


Output:



[(2, 1), (5, 4, 3), (9, 8, 7, 6)]

 
Method #2 : Using reversed()

The in-built reversed() method of Python can also be used to reverse each tuple within list.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to Reverse 
# each tuple in a list of tuples
  
def reverseTuple(lstOfTuple):
      
    return [tuple(reversed(tup)) for tup in lstOfTuple]
              
# Driver code
lstOfTuple = [(1, 2), (3, 4, 5), (6, 7, 8, 9)]
print(reverseTuple(lstOfTuple))

chevron_right


Output:

[(2, 1), (5, 4, 3), (9, 8, 7, 6)]

 
Method #3 : Using map() function

Python map() function can also serve the purpose by mapping negative-step slicing to list of tuples.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to Reverse 
# each tuple in a list of tuples
  
def reverseTuple(lstOfTuple):
      
    return list(map(lambda tup: tup[::-1], lstOfTuple))
              
# Driver code
lstOfTuple = [(1, 2), (3, 4, 5), (6, 7, 8, 9)]
print(reverseTuple(lstOfTuple))

chevron_right


Output:

[(2, 1), (5, 4, 3), (9, 8, 7, 6)]

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up


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.