Reverse each tuple in a list of tuples in Python

Introduction

If you happen to be in possession of a grouping of paired items, and you need to alter the order whereby each element it contains appears individually then some Python tricks could be employed. Let us look into deeper..

Tuples in python

In Python, tuples are simply an ordered collection of fixed elements meaning that they cannot be altered once they have been created and are defined by using parentheses'( )’. They are used for organizing linked data.

Example

my_tuple = (1,2,3)

Reversing a tuple in python

In Python, one can employ list comprehension in combination with tuple unpacking to reorder elements of a tuple each by reversing every tuple within a given list. The following part contains an example:

Example

reversed_tuple = tuple(reversed(my_tuple))

An iterator is returned by reversed(original_tuple) which gives the elements of original_tuple in reverse order. The iterator is then converted back into a tuple using the tuple function resulting in reversed_tuple having (3, 2, 1).

Reversed() built-in method

The function built-in to Python named reversed(); its main purpose is that it flips your sequence by flipping it. The mechanics behind it are simple enough as well as straightforward enough, which we will delve into briefly here below.

Additionally included is an example on how to utilize it on the latter part.

Program

#original list containing elements
my_tuple = [(1,2),(3,4),(4,5)]
#reversing using reversed() builtin method
reversed_list=[tuple(reversed(t)) for t in my_tuple]
print(reversed_list)

Output

[(2, 1), (4, 3), (5, 4)]

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top