ScanSkill

Swap Two Variables With and Without a Third Variable in Python

This article covers examples to swap two variables with and without a third variable, entered by the user at the run-time of the program.

  • Swap two variables using a third variable
  • Swap two variables without using a third variable

Prerequisites

Examples

Swap two variables using a third variable

In this, two variables var1 and var2 are assigned values taken from user input at the run-time of the program. Then the third variable x is used to swap their values.

print("Enter values for two variables...")
var1 = input("Enter the value for first: ")
var2 = input("Enter the value for second: ")

print("\\nValues before swap:")
print(f"Value of var1 = {var1}")
print(f"Value of var2 = {var2}")

x = var1
var1 = var2
var2 = x

print("\\nValues after swap:")
print(f"Value of var1 = {var1}")
print(f"Value of var2 = {var2}")

Here, the f-string is a string literal that is used as an f at the beginning and curly braces containing expression that will be replaced with its value.

Also, in print() function \n is a newline character that adds a new line.

Output:

Enter values for two variables...
Enter the value for first: 55
Enter the value for second: 44

Values before swap:
Value of var1 = 55
Value of var2 = 44

Values after swap:
Value of var1 = 44
Value of var2 = 55

Swap two variables without using a third variable

In this, two variables var1 and var2 are assigned values taken from user input at the run-time of the program. But no third variable is used to swap their values.

Just replace the following part from the above program:

x = var1
var1 = var2
var2 = x

with the following one:

var1, var2 = var2, var1

Here, the value of var1 gets initialized to var2 and vice-versa.

Final code:

print("Enter values for two variables...")
var1 = input("Enter the value for first: ")
var2 = input("Enter the value for second: ")

print("\\nValues before swap:")
print(f"Value of var1 = {var1}")
print(f"Value of var2 = {var2}")

# Swap values
var1, var2 = var2, var1

print("\\nValues after swap:")
print(f"Value of var1 = {var1}")
print(f"Value of var2 = {var2}")

Output:

Enter values for two variables...
Enter the value for first: 55
Enter the value for second: 44

Values before swap:
Value of var1 = 55
Value of var2 = 44

Values after swap:
Value of var1 = 44
Value of var2 = 55

Conclusion

In this, we just use two different methods to swap two variables in python — using and without using a third variable.