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
["oranges", "grapes", "bananas"], swap elements at the index
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 list fruits = ["oranges", "grapes", "bananas"] print("List of fruits before swap:") print(fruits) #swap elements at index 0 and 2 fruits, fruits = fruits, fruits print("\nList of fruits after swap:") print(fruits)
In the code snippet above,
2using the multivariable assignment feature in python. It will assign the value present at the index
2to the index
View all Courses