In this article, we will explore various methods to swap two elements in a list in Python.
Using Multiple Assignment
a = [10, 20, 30, 40, 50]
a[0], a[4] = a[4], a[0]
print(a)
Output
[50, 20, 30, 40, 10]
Explanation: a[0], a[4] = a[4], a[0]: swaps the first (a[0]) and last (a[4]) elements of the list.
Using XOR Operator
We can swap two numbers without requiring a temporary variable by using the XOR operator (^). It works because applying XOR twice with the same value brings back the original number.
a = 5
b = 10
a = a ^ b
b = a ^ b
a = a ^ b
print(a, b)
Output
10 5
Explanation:
- a = a ^ b: stores the XOR of a and b in a.
- b = a ^ b: effectively assigns the original value of a to b.
- a = a ^ b: assigns the original value of b to a.
Using a Temporary Variable
a = [10, 20, 30, 40, 50]
temp = a[2]
a[2] = a[4]
a[4] = temp
print(a)
Output
[10, 20, 50, 40, 30]
Explanation:
- We store the value at index 2 (30) in a temporary variable temp.
- We then assign the value at index 4 (50) to index 2.
- Finally, we assign the value stored in temp (30) to index 4.