VOOZH about

URL: https://www.geeksforgeeks.org/python/python-reversing-tuple/

⇱ Python - Reversing a Tuple - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python - Reversing a Tuple

Last Updated : 19 Feb, 2025

We are given a tuple and our task is to reverse whole tuple. For example, tuple t = (1, 2, 3, 4, 5) so after reversing the tuple the resultant output should be (5, 4, 3, 2, 1).

Using Slicing

Most common and Pythonic way to reverse a tuple is by using slicing with a step of -1, here is how we can do it:


Output
(5, 4, 3, 2, 1)

Explanation:

  • t[::-1] creates a new tuple by iterating through t in reverse order.
  • Original tuple t remains unchanged and reversed tuple is stored in rev.

Using reversed()

reversed() function returns an iterator that can be converted to a tuple.


Output
(5, 4, 3, 2, 1)

Explanation:

  • reversed(t) returns an iterator that iterates through tuple in reverse order.
  • tuple(reversed(t)) converts reversed iterator into a new tuple without modifying the original tuple.

Using a Loop

We can manually reverse the tuple by iterating from the end using a loop.


Output
(5, 4, 3, 2, 1)

Explanation:

  • range(len(t) - 1, -1, -1) generates indices from the last element to the first, allowing element access in reverse order.
  • Generator expression collects these elements into a new tuple ensuring the original tuple remains unmodified.

Using collections.deque

In this method we are using collections.deque, which provides a reverse() method for in-place reversal of the tuple.


Output
(5, 4, 3, 2, 1)

Explanation:

  • deque(t) allows efficient in-place reversal with its reverse() method avoiding the need for additional looping or slicing.
  • tuple(deq) converts the reversed deque back to a tuple ensuring the result is a new tuple while leaving the original tuple unmodified.
Comment
Article Tags:
Article Tags: