Python program to swap two elements in a list
In this article, we will learn to swap the two-element in a list using the python program.
Explanation
List = [13, 21, 24, 55, 64, 74]
Position_1 = 2
Position_2 = 4
So, the new list after swaping the elements is:
List = [13, 55, 24, 21, 64, 74]
#Code :
Program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | # make a function to swap the two elements def swap(list, pos1, pos2): # swap the position_1 element with position_2 list[pos1], list[pos2] = list[pos2], list[pos1] # return the list return list # initilize the array list = [13, 21, 24, 55, 64, 74] pos1 = 2 pos2 = 4 # print the result print(swap(list, pos1-1, pos2-1)) |
Output
[13, 55, 24, 21, 64, 74]