python swapping two variables code example

Example 1: code to swap in python

a=5
b=10
a,b=b,a  #swapped

Example 2: swapping variables in python

a = 1
b = 2

a, b = b, a
# a = 2 , b = 1

Example 3: python swap numbers

# Swap without using any temp variable
x = 66
y = 77 

print("Original: ", x,y)

x = x - y
y = x + y
x = y - x 

print("Swapped 1st time: ", x,y)

x = x + y
y = x - y
x = x - y 

print("Swapped 2nd time: ", x,y)

# Output:
# Original:  66 77
# Swapped 1st time:  77 66
# Swapped 2nd time:  66 77

Example 4: python swap two variables

a = 2
b = 4
print (a) # 2
print (b) # 4
# Now swap them
# Hold one variable in c temporarily:
c = b
b = a
a = c
# Now delete variable c from memory:
del c

print (a) # 4
print (b) # 2