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.
# 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)) |
[(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.
# 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)) |
[(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.
# 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)) |
[(2, 1), (5, 4, 3), (9, 8, 7, 6)]
Recommended Posts:
- Python program to create a list of tuples from given list having number and its cube in each tuple
- Python | Remove tuple from list of tuples if not containing any character
- Python | Group by matching second tuple value in list of tuples
- Python | Check if element is present in tuple of tuples
- Python | Remove duplicate tuples from list of tuples
- Python | Remove tuples having duplicate first value from given list of tuples
- Python | Find the tuples containing the given element from a list of tuples
- Python | Count tuples occurrence in list of tuples
- Python | Remove tuples from list of tuples if greater than n
- Python | Combining tuples in list of tuples
- Python | Convert list of strings to list of tuples
- Python | Convert list of tuples to list of strings
- Python | Convert list of tuples to list of list
- Python | Pair and combine nested list to tuple list
- Python | Merge list of tuple into list by joining the strings
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.



