In this article, we will show how to write a Python program to swap two items or elements in a List with examples. The below program uses the assignment operator to perform the multiple assignment. It will swap the item at the first index position with the third position.
a = [10, 25, 50, 75, 100]
print(a)
a[1], a[3] = a[3], a[1]
print(a)
[10, 25, 50, 75, 100]
[10, 75, 50, 25, 100]
Similarly, you can use the negative index position values to swap the last values with the first values. The program below swaps the last but one element with the second list item.
a = [10, 25, 50, 75, 100, 125, 150]
print(a)
a[-2], a[2] = a[2], a[-2]
print(a)
[10, 25, 50, 75, 100, 125, 150]
[10, 25, 125, 75, 100, 50, 150]
One of the most used and traditional approaches of swapping two list elements is by using the temporary or temp variable. The below Python program declares an integer list of seven elements to swap two items or elements. Next, reuse the 5th temp variable to swap the third value with the last item. Here,
temp = a[2] = 50
a[2] = a[6] = 150
a[6] = temp = 50
a = [10, 25, 50, 75, 100, 125, 150]
print(a)
temp = a[2]
a[2] = a[6]
a[6] = temp
print(a)