![]() |
VOOZH | about |
In this article, we will explore various methods to swap two elements in a list in Python.
[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.
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.
10 5
Explanation:
[10, 20, 50, 40, 30]
Explanation: