Easy Tutorial
❮ Python Largest Number Python Os Fchmod ❯

Python Variable Swap

Python3 Examples

The following example takes two variables from user input and swaps them:

Example

# -*- coding: UTF-8 -*-

# Filename : test.py
# author by : www.tutorialpro.org

# User input

x = input('Enter the value of x: ')
y = input('Enter the value of y: ')

# Create a temporary variable and swap
temp = x
x = y
y = temp

print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))

Executing the above code will output:

Enter the value of x: 2
Enter the value of y: 3
The value of x after swapping: 3
The value of y after swapping: 2

In the above example, we created a temporary variable temp and stored the value of x in temp, then assigned the value of y to x, and finally assigned temp to y.

Without Using a Temporary Variable

We can also swap variables without creating a temporary variable, using a very elegant method:

x, y = y, x

So the above example can be modified to:

Example

# -*- coding: UTF-8 -*-

# Filename : test.py
# author by : www.tutorialpro.org

# User input

x = input('Enter the value of x: ')
y = input('Enter the value of y: ')

# Without using a temporary variable
x, y = y, x

print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))

Executing the above code will output:

Enter the value of x: 1
Enter the value of y: 2
The value of x after swapping: 2
The value of y after swapping: 1

Python3 Examples

❮ Python Largest Number Python Os Fchmod ❯