How to swap elements in a List in Python : Various Methods

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[0]
sample_list[0] = sample_list[2]
sample_list[2] = temp

print(sample_list)

Output

swapping elements using a temporary variable
swapping elements using a temporary variable

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[0], sample_list[2] = sample_list[2], sample_list[0]
print(sample_list)

Output

swapping elements using tuple unpacking
swapping elements using tuple unpacking

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)

Output

swapping elements using list slicing
swapping elements using list slicing

Conclusion

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.

Hi, I am CodeTheBest. Here you will learn the best coding tutorials on the latest technologies like a flutter, react js, python, Julia, and many more in a single place.

SPECIAL OFFER!

This Offer is Limited! Grab your Discount!
15000 ChatGPT Prompts
Offer Expires In:
close-link