Python Examples

Python - Swap two numbers



There are two common ways to swap the value of two variables:

  • Swap the value of two variables using a temporary variable
  • Swap the value of two variables without using temporary variable

Method 1: Swap the value of two variables using a temporary variable

In the example below, the initial value of variables x and y are 10 and 25. A temporary variable called temp is created to store the value of x and then the value of y is assigned to x. Finally, value of temp (which stores values of x) is assigned to variable y. The final value of variables x and y after swap are 25 and 10 respectively.

def swap(x, y):
  print("Before Swap.")
  print("x =",x)
  print("y =",y)

  #Swap technique
  temp = x
  x = y
  y = temp

  print("After Swap.")
  print("x =",x)
  print("y =",y)

swap(10, 25)

The above code will give the following output:

Before Swap.
x = 10
y = 25
After Swap.
x = 25
y = 10

Method 2: Swap the value of two variables without using temporary variable

+ operator is used to swap the value of two variables. In this method no temporary variable is used. See the example below for syntax.

def swap(x, y):
  print("Before Swap.")
  print("x =",x)
  print("y =",y)

  #Swap technique
  x = x + y
  y = x - y
  x = x - y

  print("After Swap.")
  print("x =",x)
  print("y =",y)

swap(10, 25)

The above code will give the following output:

Before Swap.
x = 10
y = 25
After Swap.
x = 25
y = 10

Similarly, others operators can also be used in this method. Please see the page: Python - Swap two numbers without using Temporary Variable.

Method 3: Swap the value of two variables using = operator

In python, the value of two variables can be swapped using assignment operator also. See the example below for syntax.

x = 10
y = 25

print("Before Swap.")
print("x =",x)
print("y =",y)

#Swap technique
x , y = y, x

print("After Swap.")
print("x =",x)
print("y =",y)

The above code will give the following output:

Before Swap.
x = 10
y = 25
After Swap.
x = 25
y = 10