Exchanging the positions of two elements within a list is known as swapping elements in a list. Python offers multiple methods for executing this swap. In this tutorial, you will know how to swap elements in a list in Python using various methods.
Methods to swap elements in a List in Python
Lets know all the methods that will be implemented in this tutorial.
Method 1: Using a temporary variable
The first method is the use of a temporary variable. This method use a temporary variable to hold the value of one of the elements while swapping.
Execute the below lines of code to swap the elements in a list.
sample_list = [1, 2, 3, 4] temp = sample_list sample_list = sample_list sample_list = temp print(sample_list)
In this example, I am swapping the first and third elements using a temporary variable.
Method 2: Swap elements in a List in Python Using tuple unpacking
The second method to swap the elements is through a tuple. Tuple is a data structure that is the same as a list but here the square bracket is use to store the variables.
Here the tuple will be unpacked for the elements I want to swap.
If I have to swap the first and third elements then I will use the below lines of code.
sample_list = [1, 2, 3, 4] sample_list, sample_list = sample_list, sample_list print(sample_list)
Method 3: Using list slicing
You can also use list slicing to swap the position of the elements of the list. The process is the same as the above method. Instead of the tuple, you will use the “:” to unpack the elements.
Run the below lines of code to swap the elements
sample_list = [1, 2, 3, 4] sample_list[0:2], sample_list[2:4] = sample_list[2:4], sample_list[0:2] print(sample_list)
You may require to swap the elements of the list while coding. The above methods will be useful for swapping. You can use any of them according to your choice. One thing you should note is that if you use the above methods then the original lists will be modified also. It means the position of the elements will change.