![]() |
VOOZH | about |
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)]
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.
[(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 .
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.
[(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 .
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.
[(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.
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.
[(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 .