Reverse a tuple in Python

avatar

Borislav Hadzhiev

Last updated: Jun 27, 2022

banner

Photo from Unsplash

Reverse a tuple in Python #

To reverse a tuple in Python:

  1. Pass the tuple to the reversed() function.
  2. The reversed function returns a reverse iterator object.
  3. Pass the reverse iterator object to the tuple() class to convert it to a tuple.
main.py
my_tuple = ('a', 'b', 'c') reversed_tuple = tuple(reversed(my_tuple)) # 👇️ ('c', 'b', 'a') print(reversed_tuple)
Tuples are very similar to lists, but implement fewer built-in methods and are immutable (cannot be changed).

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.

The reversed function takes a sequence and returns a reverse iterator object.

If you need to convert the reverse object to a tuple, pass it to the tuple() class.

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.

main.py
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.

main.py
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 my_tuple[start:stop:step].

We omitted the indices for start and stop because we want the whole tuple.

We used -1 for the step which 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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.