Join my Laravel for REST API's course on Udemy 👀

Swapping list items in Python

October 30, 2020  ‐ 1 min read

Suppose you have a list in Python, and you want to swap the positions of items in the list.

Lets take the following list for example. In which the items are clearly out of order.

meals = ['breakfast', 'dinner', 'lunch']

In order to the swap the positions of items in a list we need to find the indexes of the items we'd like to swap. We can easily do so in this case by using the index() function available for lists.

i, j = meals.index('dinner'), meals.index('lunch')

In this case we want to swap 'dinner' at index 1 with 'lunch' at index 2. These indexes are now stored in the variables i and j.

In Python a sweet one-liner will suffice to swap the items in the list.

meals[i], meals[j] = meals[j], meals[i]

This puts the list meals in the proper order.

meals = ['breakfast', 'dinner', 'lunch']
i, j = meals.index('dinner'), meals.index('lunch')
meals[i], meals[j] = meals[j], meals[i]

print(meals)
# => ['breakfast', 'lunch', 'dinner']

Be aware that this works for lists, and not tuples. Since tuples are not mutable and lists are.