Python Tutorials

Python Programs

Python Swap Two Numbers


Python Swap Two Numbers

In this tutorial, we will learn how to write a program to swap two numbers in Python. We will cover two methods: using a temporary variable and using tuple unpacking to swap the values of two variables.


What is Swapping

Swapping refers to the process of exchanging the values of two variables. This can be useful in various programming scenarios where the order or value of variables needs to be interchanged.


Syntax

The syntax to swap two numbers in Python can be done in two ways:

# using a temporary variable
temp = a
a = b
b = temp

# using tuple unpacking
a, b = b, a


Swapping two numbers using a temporary variable

We can use a temporary variable to swap the values of two variables.

For example,

  1. Declare two variables, a and b, and assign them values.
  2. Use a temporary variable temp to hold the value of a.
  3. Assign the value of b to a.
  4. Assign the value of temp (original value of a) to b.
  5. Print the values of a and b to verify they have been swapped.

Python Program

a = 5
b = 10

# Swap the values using a temporary variable
temp = a
a = b
b = temp

# Print the swapped values
print('a =', a)
print('b =', b)

Output

a = 10
b = 5


Swapping two numbers using tuple unpacking

We can use tuple unpacking to swap the values of two variables in a single line.

For example,

  1. Declare two variables, a and b, and assign them values.
  2. Use tuple unpacking to swap the values of a and b in a single line.
  3. Print the values of a and b to verify they have been swapped.

Python Program

a = 5
b = 10

# Swap the values using tuple unpacking
a, b = b, a

# Print the swapped values
print('a =', a)
print('b =', b)

Output

a = 10
b = 5