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 SlicingMost common and Pythonic way to reverse a tuple is by using slicing with a step of -1, here is how we can do it:
Python
t = (1, 2, 3, 4, 5)
# Reverse the tuple using slicing with a step of -1
rev = t[::-1]
print(rev)
Explanation:
reversed() function returns an iterator that can be converted to a tuple.
Python
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)
Explanation:
We can manually reverse the tuple by iterating from the end using a loop.
Python
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)
Explanation:
In this method we are using collections.deque, which provides a reverse() method for in-place reversal of the tuple.
Python
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)
Explanation:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4