Python program to swap two elements in a list using the index
We will take a list and two indexes (for swapping ) from the user and then swap the values at the given index in the list.
Example:
Sample Input:
[3, 1, 0, 9, 23, 89, 10] , 2, 5
Output:
[3, 1, 89, 9, 23, 0, 10]
Method 1: Simply swap values using comma separator
We will swap the elements directly using the common swapping method.
Syntax:
Program to swap any two elements in the list
Output:
Method 2: Pop values and then inserting them back
One more method to swap values is to pop out values at a given index and then insert them back to the given index.
Algorithm :
Program to swap any two elements in the list
Output:
Swapping two values based on their values entered by the user
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer