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
test_list = [(3, 4), (6, 5), (7, 8)]
print("The original list is : " + str(test_list))
res = [(sub[1], sub[0]) for sub in test_list]
print("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)]
Time Complexity: O(n) where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n), where n is the number of elements in the new res list
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
test_list = [(3, 4), (6, 5), (7, 8)]
print("The original list is : " + str(test_list))
res = list(map(lambda sub: (sub[1], sub[0]), test_list))
print("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)]
Time Complexity: O(n) where n is the number of elements in the list “res_list”.
Auxiliary Space: O(n), where n is the number of elements in the new res list
Method #3 : Using list(),reverse() and tuple() methods
- Initiated a for loop to traverse the list
- Converted each tuple to list and used reverse() to swap elements
- Converted the list again to tuple and appended to output list
- Displayed the output list
Python3
test_list = [(3, 4), (6, 5), (7, 8)]
print("The original list is : " + str(test_list))
res=[]
for i in test_list:
x=list(i)
x.reverse()
res.append(tuple(x))
print("The swapped tuple list is : " + str(res))
|
OutputThe original list is : [(3, 4), (6, 5), (7, 8)]
The swapped tuple list is : [(4, 3), (5, 6), (8, 7)]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 4: using a simple for loop:
Python3
test_list = [(3, 4), (6, 5), (7, 8)]
print("The original list is : " + str(test_list))
res = []
for i in test_list:
x, y = i
res.append((y, x))
print("The swapped tuple list is : " + str(res))
|
OutputThe original list is : [(3, 4), (6, 5), (7, 8)]
The swapped tuple list is : [(4, 3), (5, 6), (8, 7)]
Time complexity: O(n), where n is the number of tuples in the list,
Auxiliary space: O(n) because we are creating a new list of the same length as the original list.
Last Updated :
06 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...