In this shot, we will learn how to swap two elements in a list using python.
Let's start with an 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.
#given listfruits = ["oranges", "grapes", "bananas"]print("List of fruits before swap:")print(fruits)#swap elements at index 0 and 2fruits[0], fruits[2] = fruits[2], fruits[0]print("\nList of fruits after swap:")print(fruits)
In the code snippet above,
fruits
.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.