How to Invert Python Tuple Elements?


Python tuples store data in the form of individual elements. The order of these elements is fixed i.e (1,2,3) will remain in the same order of 1,2,3 always. In this article, we are going to see how to invert python tuple elements or in simple terms how to reverse the order of the elements.

Let us 1st see a sample input and output −

Input

(5,6,7,8)

Output

(8,7,6,5)

Let us now explore the various ways to invert tuple elements.

Method 1: Using Tuple Slicing

Slicing is a way of extracting subsets of elements from a tuple. It has a start and stop which help us determine where to start the subset and where to end it at. It also uses an optional parameter called step which specifies the step size which is 1 by default. We make use of this optional parameter by setting it as -1 which means it would go in the reverse order by taking all elements of the tuple.

Example

original_tuple = (1, 2, 3, 4, 5)
inverted_tuple = original_tuple[::-1]

print("Original tuple=",original_tuple)

print("Inverted tuple=",inverted_tuple)

Output

Original tuple= (1, 2, 3, 4, 5)
Inverted tuple= (5, 4, 3, 2, 1)

Method 2: Using the reversed() Function

The reverse function effectively admits numerous types of iterables, such as strings or lists, even tuples. Its outcome presents a novel iterator that allows traversal of elements in reverse rather than original order. Essential to highlight here is this technique's nature of not modifying the iterable initially provided but forging one anew and presenting it upon completion.

Example

original_tuple = (1, 2, 3, 4, 5)
inverted_tuple = tuple(reversed(original_tuple))

print("Original tuple=",original_tuple)
print("Inverted tuple=",inverted_tuple)

Output

Original tuple= (1, 2, 3, 4, 5)
Inverted tuple= (5, 4, 3, 2, 1)

Method 3: Using a loop

This is a very simple approach. Here we initialize an empty list and then use a for loop to iterate over the tuple. For every iteration we insert the element at position 0 and hence the previously added elements move towards the right which effectively reverses the tuple but stores it in a list form. We the simply convert it to a tuple using tuple(iterable).

Example

original_tuple = (1, 2, 3, 4, 5)
inverted_list = []

for item in original_tuple:
   inverted_list.insert(0, item)
inverted_tuple = tuple(inverted_list)

print("Original tuple=",original_tuple)
print("Inverted tuple=",inverted_tuple)

Output

Original tuple= (1, 2, 3, 4, 5)
Inverted tuple= (5, 4, 3, 2, 1)

Method 4: Using Extended Unpacking

Python's capability to allow us to assign multiple values from an iterable into a single variable, known as extended unpacking, is quite useful. It basically involves using the * operator. But here's the catch - you can only indulge in this efficient programming technique if your python version is 3.6 or higher.

Example

original_tuple = (1, 2, 3, 4, 5)
*inverted_elements, = original_tuple[::-1]
inverted_tuple = tuple(inverted_elements)

print("Original tuple=",original_tuple)
print("Inverted tuple=",inverted_tuple)

Output

Original tuple= (1, 2, 3, 4, 5)
Inverted tuple= (5, 4, 3, 2, 1)

Method 5: Using list Comprehension

List comprehensions are just a way to generate lists, in this case for creating a list that contains the reversed elements of a tuple. As the name implies the output is, in list format so we have simply utilized the tuple(iterable) function to convert it into the desired format.

Example

original_tuple = (1, 2, 3, 4, 5)
inverted_tuple= tuple([original_tuple[i] for i in range(len(original_tuple)-1, -1, -1)])

print("Original tuple=",original_tuple)
print("Inverted tuple=",inverted_tuple)

Output

Original tuple= (1, 2, 3, 4, 5)
Inverted tuple= (5, 4, 3, 2, 1)

Method 6: Using lambda Expression

Lambda expression are 1 liner function which are mainly used for simple operations like this one. Our lambda expression will be mapped to the reversed() function used earlier and will require an input ‘c’ which will be the input/original tuple and will return the tuple with elements reversed.

Its syntax is lambda arguments: expression

Example

original_tuple = (1, 2, 3, 4, 5)
a=lambda c: tuple(reversed(original_tuple))
inverted_tuple=a(original_tuple)

print("Original tuple=",original_tuple)
print("Inverted tuple=",inverted_tuple)

Output

Original tuple= (1, 2, 3, 4, 5)
Inverted tuple= (5, 4, 3, 2, 1)

Method 7: Using Numpy Module

Numpy which is commonly used for handling single and multi-dimensional arrays of data is used here along with its flip method. Initially we need to convert the input/original tuple to a numpy array and then flip it using the flip() method. After that we convert it back to a tuple and the print the results.

Example

import numpy as np

original_tuple = (1, 2, 3, 4, 5)
original_array = np.array(original_tuple)

# Reverse the NumPy array
inverted_array = np.flip(original_array)
inverted_tuple = tuple(inverted_array)

print("Original tuple:", original_tuple)
print("Inverted tuple:", inverted_tuple)

Output

Original tuple= (1, 2, 3, 4, 5)
Inverted tuple= (5, 4, 3, 2, 1)

Method 8: Using the reduce() Function

The reduce() function belongs to the functools module of python. Its use case for reversing tuple elements is important and as shown below.

Example

from functools import reduce

original_tuple = (1, 2, 3, 4, 5)

# Define a lambda function to invert elements
invert_fn = lambda acc, x: (x,) + acc

# Use reduce to invert the tuple
inverted_tuple = reduce(invert_fn, original_tuple, ())

print("Original tuple:", original_tuple)
print("Inverted tuple:", inverted_tuple)

Output

Original tuple= (1, 2, 3, 4, 5)
Inverted tuple= (5, 4, 3, 2, 1)

Method 9: Using join function with negative indexing

This method reverses the tuple using the negative index slicing and then joins the elements using the join function. The drawback of this method is that it works only on those tuples which have string elements and the join functions output it also a string which is converted to a tuple.

Example

input_tuple=("p", "o", "i", "n", "t")
inverted_tuple=tuple("".join(input_tuple)[::-1])

print("Original tuple:", input_tuple)
print("Inverted tuple:", inverted_tuple)

Output

Original tuple: ('p', 'o', 'i', 'n', 't')
Inverted tuple: ('t', 'n', 'i', 'o', 'p')

Conclusion

Tuples are basically an ordered, immutable collection of elements which are somewhat similar to lists. They can hold a mix of data types as well. In order to reverse the elements of the tuples, we have demonstrated 9 methods in this article. While this inverting is a straightforward code it is a very good point of learning for beginners in python.

Updated on: 02-Nov-2023

70 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements