Open In App

Swap tuple elements in list of tuples - Python

Last Updated : 11 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The task of swapping tuple elements in a list of tuples in Python involves exchanging the positions of elements within each tuple while maintaining the list structure. Given a list of tuples, the goal is to swap the first and second elements in every tuple. For example, with a = [(3, 4), (6, 5), (7, 8)], the result would be [(4, 3), (5, 6), (8, 7)]

Using list comprehension

List comprehension is the most efficient and readable way to swap tuple elements in a list. It iterates through the list and swaps each tuple’s elements in a single step, making the code concise and fast.

Python
a = [(3, 4), (6, 5), (7, 8)]
res = [(x, y) for y, x in a]  # Swaps elements using tuple unpacking

print(res)

Output
[(4, 3), (5, 6), (8, 7)]

Explanation: For each tuple (x, y), it swaps the elements using tuple unpacking (y, x → x, y). The modified tuples are stored in res .

Using map()

map() applies a swapping operation to each tuple using a lambda function. This method is useful when working with large datasets, as it processes elements efficiently without creating an intermediate list during iteration.

Python
a = [(3, 4), (6, 5), (7, 8)]
res = list(map(lambda sub: (sub[1], sub[0]), a))

print(res)

Output
[(4, 3), (5, 6), (8, 7)]

Explanation: map() apply a lambda function to each tuple in the list a. It swaps the elements by accessing them as sub[1], sub[0]. The map() result is converted to a list and stored in res .

Using zip()

This method swaps tuple elements by first unpacking them using zip(*a), then reconstructing the list. While not the most efficient, it can be helpful when dealing with structured transformations in tuple-based data.

Python
a = [(3, 4), (6, 5), (7, 8)]

res = list(zip(*[(y, x) for x, y in a]))
res = list(zip(res[0], res[1]))  # Convert back to list of tuples

print(res)

Output
[(4, 3), (5, 6), (8, 7)]

Explanation: This code swaps tuple elements using list comprehension, then transposes them with zip(*...). The second zip() reconstructs the list of swapped tuples, which is then printed.

Using for loop

for loop manually iterates through the list, swaps elements, and appends the modified tuples to a new list. While easy to understand, it is slower than other methods due to explicit list operations and function calls.

Python
a = [(3, 4), (6, 5), (7, 8)]
res = []

for x, y in a:
    res.append((y, x))  # Manually swapping elements
print(res)

Output
[(4, 3), (5, 6), (8, 7)]

Explanation: for loop iterates through each tuple in a, manually swaps the elements (y, x) and appends the swapped tuple to res .


Next Article
Practice Tags :

Similar Reads