How to swap two items in a list in Python

In this post, I’m gonna show how to swap two items in a list.

This post is an extension of How to swap two variables in Python.

Swap by index

This first code snippet assumes you already know the index of the elements you want to swap.

Just use the tuple syntax to assign the values on the right side to the positions on the left side.

Thus, my_list[2] on the right is assigned to my_list[0] on the left, and my_list[0] on the right is assigned to my_list[2] on the left.

This solution is pythonic, that is, a standard way to do it in Python.

my_list = ["bmw", "ferrari", "mclaren"]

my_list[0], my_list[2] = my_list[2], my_list[0]

print(my_list)
#output: ['mclaren', 'ferrari', 'bmw']

Swap by value

This second snippet assumes you only know the values you want to swap.

The logic of the swap is the same as explained before.

The only extra step is to use the index() method to find the index of the values and then use these indexes to make the swap.

Thus, my_list[mclaren_index] on the right is assigned to my_list[bmw_index] on the left, and my_list[bmw_index] on the right is assigned to my_list[mclaren_index] on the left.

my_list = ["bmw", "ferrari", "mclaren"]

bmw_index = my_list.index("bmw")
print(bmw_index)
#output: 0

mclaren_index = my_list.index("mclaren")
print(mclaren_index)
#output: 2

my_list[bmw_index], my_list[mclaren_index] = my_list[mclaren_index], my_list[bmw_index]

print(my_list)
#output: ['mclaren', 'ferrari', 'bmw']

Watch on Youtube

You can also watch this content on Youtube: