Reverse a tuple in Python

In this tutorial, we will learn how to reverse a tuple in Python with some easy examples. In many situations, you might have come up with this requirement.

I know you are here because you need this trick, so you can easily reverse a tuple using Python.

If you don’t know how to reverse a tuple in python, then you are in the right place.

slicing technique – Reverse a tuple in Python

Let’s understand the very first technique to reverse a tuple. This technique is also used with List in Python.

First of all, we are aware of the fact that tuples are immutable, so they cannot be changed in place but they can be copied, so this in mind, we use the slicing technique. We first copy the elements of the reverse Tuple to the new tuple and then print the new tuple as shown.

tuples=(1,2,3,4,5,67,8)  #assuming set of tuples
reversedTuples = tuples[::-1])    #slicing
print(reversedTuples)
Output : (8, 67, 5, 4, 3, 2, 1)

This is the reverse of tuple we used in the given input.

using in-built reversed() function in tuple

In this method, we had used reversed() inbuilt python function to reverse a tuple. This function can also be used in the same format with List in Python. Let’s understand this with the help of the shown example.

tuples=(1,2,3,4,5,67,8)
reversedTuples=tuple(reversed(tuples))
print(reversedTuples)
Output : (8, 67, 5, 4, 3, 2, 1)

This is the reverse of tuple we used in the given input.

We have to reverse the immutable tuple, which cannot be changed. Due to this property of tuple we left behind with the limited techniques to reverse a tuple. In this tutorial, we have learned about such two techniques.

Also:

Leave a Reply