- Published on
Swapping list elements using `Tuple Unpacking` in Python
- Authors
- Name
- hwahyeon
When swapping elements in a list, it's common to use a temporary variable to exchange values.
List = [1, 9]
temp = List[0]
List[0] = List[1]
List[1]= temp
However, in Python, you can easily swap values in a list using tuple unpacking.
Tuple unpacking in Python is a useful technique that allows you to assign or exchange multiple values from sequence data types like tuples or lists in a single step.
a, b = (1, 2)
print(a) # 1
print(b) # 2
In the code above, the tuple (1, 2)
is unpacked and assigned to a
and b
respectively. This process is called tuple unpacking.
x = 10
y = 20
x, y = y, x
print(x) # 20
print(y) # 10
List = [1, 9]
List[0], List[1] = List[1], List[0]
List # [9, 1]
As shown above, the swap occurs in a single line of code.
Let’s break it down further.
1. Creating a tuple on the right-hand side
List[1], List[0]
First, on the right-hand side of the assignment, Python creates a tuple (9, 1)
. At this moment, the tuple (9, 1)
is temporarily stored in memory.
2. Unpacking the tuple and assigning to variables
List[0], List[1] = (9, 1)
Python then unpacks the tuple (9, 1)
and assigns its values to List[0]
and List[1]
in sequence. Thus, the values of (9, 1)
are stored in List[0]
and List[1]
, respectively.
3. Memory management
After all the values from the tuple are assigned to the variables on the left-hand side, the tuple is removed from memory by the GC (Garbage Collection) process because there are no remaining references to that temporary tuple.
Conclusion
In reality, the values are not swapped simultaneously, instead, the tuple is created on the right-hand side and its values are sequentially unpacked and assigned to the variables on the left-hand side.