Home » Python

Reverse each tuple in a list of tuples in Python

In this tutorial, we will see how to reverse each tuple given in a list of tuples in the Python programming language?
Submitted by Bipin Kumar, on November 09, 2019

Tuples in Python are a collection of elements in a round bracket() or not but separated by commas. Tuples are similar to list in some operations like indexing, concatenation, etc. but lists are mutable whereas tuples are immutable acts like a string. Here, a list of tuples will be given by the user and we have to reverse each tuple in Python.

For example, list of tuple A=[(9,0), (2,5), (4,6), (7,1), (1,5)] is given by the user and we have to return it like [(0,9), (5,2), (6,4), (1,7), (5,1)] which have reverse of each tuples of list.

We are going to solve this problem with two approaches, the first one is by using the slicing property and another one is by using the predefined reversed() function of Python language. So, let's start simply writing the program.

1) By using the slicing property

#suppose a list of tuples provided by the user is A.

A=[(4,5), (4,6), (6,9), (3,6),(12,0), (6,7)]
B=[k[::-1] for k in A]

print('List of reversed tuples:',B)

Output

List of reversed tuples: [(5, 4), (6, 4), (9, 6), (6, 3), (0, 12), (7, 6)]

In Python, [::-1] used to reversed list, string, etc.

2) By using the reversed function of Python

The reversed() function used to reverse a list, string, etc. in Python. It acts like the above slicing property.

#suppose the same input of the above program.

A=[(4,5), (4,6), (6,9), (3,6),(12,0), (6,7)]

B=[tuple(reversed(k)) for k in A]

print('List of reversed tuples:',B)

Output

List of reversed tuples: [(5, 4), (6, 4), (9, 6), (6, 3), (0, 12), (7, 6)]



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.