Python | Swap tuple elements in list of tuples

• Last Updated : 27 Aug, 2019

While doing competitive programming, one can come across a question in which one requires to work with 2D plane and work with coordinates. One such subproblem can be swapping x, y coordinate elements. Let’s discuss certain ways in which this problem can be solved using tuple element swapping.

Method #1 : Using list comprehension
This is just a brute method to perform the longer method of loop for swapping the elements. In this a new list of tuple is created rather than an inplace swap.

 # Python3 code to demonstrate working of# Swap tuple elements in list of tuples# Using list comprehension  # initializing listtest_list = [(3, 4), (6, 5), (7, 8)]  # printing original listprint("The original list is : " + str(test_list))  # Swap tuple elements in list of tuples# Using list comprehensionres = [(sub, sub) for sub in test_list]          # printing resultprint("The swapped tuple list is : " + str(res))
Output :
The original list is : [(3, 4), (6, 5), (7, 8)]
The swapped tuple list is : [(4, 3), (5, 6), (8, 7)]

Method #2 : Using map() + lambda
Yet another way to perform this task is using map and lambda. This is a bit slower in execution but a more compact way to perform this task.

 # Python3 code to demonstrate working of# Swap tuple elements in list of tuples# Using map() + lambda  # initializing listtest_list = [(3, 4), (6, 5), (7, 8)]  # printing original listprint("The original list is : " + str(test_list))  # Swap tuple elements in list of tuples# Using map() + lambdares = list(map(lambda sub: (sub, sub), test_list))          # printing resultprint("The swapped tuple list is : " + str(res))
Output :
The original list is : [(3, 4), (6, 5), (7, 8)]
The swapped tuple list is : [(4, 3), (5, 6), (8, 7)]

My Personal Notes arrow_drop_up