Last updated: Jun 27, 2022
Photo from Unsplash
To reverse a tuple in Python:
reversedfunction returns a reverse iterator object.
reverseiterator object to the
tuple()class to convert it to a tuple.
my_tuple = ('a', 'b', 'c') reversed_tuple = tuple(reversed(my_tuple)) # 👇️ ('c', 'b', 'a') print(reversed_tuple)
Since tuples cannot be changed, the only way to reverse a tuple is to create a new tuple with the desired order of items.
We used the
reversed() built-in function to reverse a tuple.
function takes a sequence and returns a
reverse iterator object.
reverseobject to a tuple, pass it to the
The tuple class takes at most 1 argument - an iterable.
If you only need to iterate over the object, you don't have to convert it back to a tuple.
my_tuple = ('a', 'b', 'c') reversed_obj = reversed(my_tuple) for item in reversed_obj: print(item) # 👉️ c b a
Alternatively, you can use tuple slicing.
Use tuple slicing to reverse a tuple in Python, e.g.
reversed_tuple = my_tuple[::-1]. We used
-1 for the
step which means step
from the end of the tuple towards the beginning 1 item at a time.
my_tuple = ('a', 'b', 'c') reversed_tuple = my_tuple[::-1] print(reversed_tuple) # 👉️ ('c', 'b', 'a')
This approach also creates a new tuple. Tuples cannot be reversed in place because they are immutable.
The syntax for tuple slicing is
We omitted the indices for
stop because we want the whole tuple.
stepwhich means that we step from the end of the tuple towards the beginning 1 item at a time.
The original tuple remains unchanged, so make sure to store the reversed tuple in a variable.