swap elements python code example

Example 1: swapping in python

x = 5
y = 10

x, y = y, x
print("x =", x)
print("y =", y)

Example 2: swap two elements in a list python

i = ['title', 'email', 'password2', 'password1', 'first_name', 
         'last_name', 'next', 'newsletter']
    a, b = i.index('password2'), i.index('password1')
    i[b], i[a] = i[a], i[b]

Example 3: python swap function

def swap0(s1, s2):
    assert type(s1) == list and type(s2) == list
    tmp = s1[:]
    s1[:] = s2
    s2[:] = tmp
    
# However, the easier and better way to do a swap in Python is simply:
s1, s2 = s2, s1