Python - Reversing a Tuple
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:
t = (1, 2, 3, 4, 5)
# Reverse the tuple using slicing with a step of -1
rev = t[::-1]
print(rev)
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.
t = (1, 2, 3, 4, 5)
# Reverse the tuple using the built-in reversed() function and convert it back to a tuple
rev = tuple(reversed(t))
print(rev)
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.
t = (1, 2, 3, 4, 5)
# Reverse the tuple by iterating through the indices in reverse order
rev = tuple(t[i] for i in range(len(t) - 1, -1, -1))
print(rev)
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.
from collections import deque
t = (1, 2, 3, 4, 5)
deq = deque(t)
# Reverse the deque in place
deq.reverse()
# Convert the reversed deque back to a tuple
rev = tuple(deq)
print(rev)
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.