Python Program to swap adjacent elements of a list

In this program, you will learn how to swap adjacent elements of a list in Python.


while Condition:
    #Statement
    #Increment/Decrement

Python Program to swap adjacent elements of a list

Example: How to swap adjacent elements of a list in Python

data = [10, 20, 30, 40]

print("List before swap:", data)

i = 0
while i < data.__len__() - 1:
    t = data[i]
    data[i] = data[i + 1]
    data[i + 1] = t
    i = i + 2

print("List after swap:", data)

Output:

List before swap: [10, 20, 30, 40]
List after swap: [20, 10, 40, 30]