Python | Swap tuple elements in list of tuples

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.