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

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.