How to reverse a tuple in Python (2 Easy ways)
In this tutorial, we are going to learn about, how to reverse the elements of a tuple using Python.
There are some situations in which you need to reverse a tuple. In this article, I will share with you the best and simple way to reverse a tuple in python.
What is a tuple ?
In python, a tuple is an list like data structure, which consists of elements of the same types and fixed length. The length of tuple is fixed at the time of creating the tuple, once it is defined we can’t able to modify it.
Reverse a tuple in Python
To reverse a tuple in Python:
-
Create a new tuple eg: a = (1, 2, 3).
-
Pass the tuple to the built-in reversed() function.
-
Now, pass the reversed iterator object to tuple() function.
Consider, that you have the following tuple:
a = (1, 2, 3)
Here is an example, of how to reverse a tuple:
a = (1, 2, 3)
reverse_tuple = tuple(reversed(a))
print(reverse_tuple)
Output:
(3, 2, 1)
In the example above, we first passed the tuple to the built-in reversed() function. So, it returns an reverse iterable object then we passed it back to tuple() function to convert it back to tuple data structure.
The reversed() function in python accepts a sequence of elements and returns a reverse iterable object.
Similarly, we can also reverse a tuple using the slicing syntax [::-1]
in python.
Here is an example:
a = (1,2,3)
print (a[::-1])
In the example above, we have ommited the start, stop
arguments, because we require all elements in the tuple and passed step as -1
, so it creates a new tuple by beginning with the end element of a tuple goes all the way to first element.
Conclusion
In this article, I have shared with you two simplest ways to reverse a tuple.one is using the built-in reversed() method other one is using the slicing syntax.