Swapping elements of a Python list is very similar to swapping values of the variables in Python. We use the index of the items to swap the position of the items, just like variables in Python. So if you want to learn how to swap the position of items in a Python list, this article is for you. In this article, I’ll show you a tutorial on how to swap items in a Python list.
Swap Items of a Python List
As a beginner in Python, you must have written a program to swap the values of two variables that looks like a, b = b, a. Likewise, you can swap the position of items in a Python list where you will use the index instead of the variable names. So here’s how you can write a Python function to swap the position of the items of a Python list:
['Aman', 'Kharwal', 'Sajid', 'Akanksha'] ['Aman', 'Kharwal', 'Akanksha', 'Sajid']
In the code above, I defined a Python function that takes three arguments. The first argument is the name of a list assuming that the list is not empty, and contains at least two elements. The second argument is the index of the first element, which you want to swap with the index of the second element, which you will use as the third argument in this function.
Then I have defined a list of names, and in the next line, I am using the swap function to swap the values of the second and third indexes.
So this is how you can swap the items of a list. Swapping items of a Python list is very much similar to swapping the values of variables. I hope you liked this article on a tutorial on swapping items of a Python list. Feel free to ask your valuable questions in the comments section below.