Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Reverse each tuple in a list of tuples in Python
When it is required to reverse each tuple in a list of tuples, the negative step slicing can be used.
A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on). A list of tuple basically contains tuples enclosed in a list.
In negative slicing, the index is accessed using negative numbers, instead of positive ones. The slice notation [::-1] reverses the order of elements in each tuple.
Using List Comprehension with Negative Slicing
Below is a demonstration for the same ?
def reverse_tuple(my_tuple):
return [tup[::-1] for tup in my_tuple]
my_list = [(21, 22), (43, 74, 45), (76, 17, 98, 19)]
print("The list of tuples is")
print(my_list)
print("The reversed list of tuples is")
print(reverse_tuple(my_list))
The list of tuples is [(21, 22), (43, 74, 45), (76, 17, 98, 19)] The reversed list of tuples is [(22, 21), (45, 74, 43), (19, 98, 17, 76)]
Using the reversed() Function
Another approach is to use the built-in reversed() function ?
def reverse_with_reversed(tuple_list):
return [tuple(reversed(tup)) for tup in tuple_list]
my_list = [(21, 22), (43, 74, 45), (76, 17, 98, 19)]
result = reverse_with_reversed(my_list)
print("Original list:", my_list)
print("Reversed tuples:", result)
Original list: [(21, 22), (43, 74, 45), (76, 17, 98, 19)] Reversed tuples: [(22, 21), (45, 74, 43), (19, 98, 17, 76)]
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
Slice [::-1]
|
High | Faster | Simple reversing |
reversed() |
High | Slightly slower | Explicit intent |
How It Works
- The method
reverse_tupletakes a list of tuples as parameter - It iterates through each tuple using list comprehension
- The slice notation
[::-1]reverses each tuple by stepping backward - Returns a new list with all tuples reversed
Conclusion
Both slice notation [::-1] and reversed() effectively reverse tuples in a list. The slice method is more concise and slightly faster for this specific use case.
