To reverse a tuple in Python, the easiest way is slicing.
t = (0, 1, 2, 3)
t_reversed = t[::-1]
print(t_reversed)
#Output:
(3, 2, 1, 0)
You can also use reversed() to create a reversed object and build a new tuple from scratch.
t = (0, 1, 2, 3)
new_tuple = ()
for x in reversed(t):
new_tuple = new_tuple + (x,)
print(new_tuple)
#Output:
(3, 2, 1, 0)
When working with collections of data in Python, the ability to change the order of the elements in your data easily can be useful.
One such operation is reversing the order of your data.
Tuples are a commonly used type of object used to store data in Python and sometimes it can make sense to want to reverse the order of the elements in a tuple.
Unfortunately, unlike with a list object, tuples do not have a function like reverse().
Instead, the easiest way to reverse a tuple in Python is with slicing.
Below is a simple example showing you how to reverse a tuple variable with Python.
t = (0, 1, 2, 3)
t_reversed = t[::-1]
print(t_reversed)
#Output:
(3, 2, 1, 0)
Reversing Tuple Variable with reversed() in Python
You can also use the Python built-in function reversed() to reverse a tuple in Python.
Below is a simple example showing you how to reverse a tuple in Python with reversed() and a loop.
t = (0, 1, 2, 3)
new_tuple = ()
for x in reversed(t):
new_tuple = new_tuple + (x,)
print(new_tuple)
#Output:
(3, 2, 1, 0)
Hopefully this article has been useful for you to learn how to reverse tuples in your Python code.