How to swap two elements in a list in python

In this shot, we will learn how to swap two elements in a list using python.

Let's start with an example.

Example

Given a list of fruits = ["oranges", "grapes", "bananas"], swap elements at the index 0 and 2.

After swapping the elements at the given indices, we will get the list as below.

['bananas', 'grapes', 'oranges'].

We can swap two elements in a list using the multivariable assignment feature in Python.

We can assign two variables at a time by comma-separated as below.

a,b = 1,2

In the same way, we can swap the elements in a list.

Code

#given list
fruits = ["oranges", "grapes", "bananas"]
print("List of fruits before swap:")
print(fruits)
#swap elements at index 0 and 2
fruits[0], fruits[2] = fruits[2], fruits[0]
print("\nList of fruits after swap:")
print(fruits)

Explanation

In the code snippet above,

  • Line 2: We declare and initialize the list fruits.
  • Line 5: We display the list before the swap operation.
  • Line 8: We swap elements at the index 0 and 2 using the multivariable assignment feature in python. It will assign the value present at the index 2 to the index 0 and vice-versa.
  • Line 11: We display the list after the swap operation.

Free Resources