YouTip LogoYouTip

Python3 Swap Variables

# Create a temporary variable and swap temp = x x = y y = temp print('Value of x after swap: {}'.format(x)) print('Value of y after swap: {}'.format(y))

Executing the above code produces the following output:

Enter value for x: 2
Enter value for y: 3
Value of x after swap: 3
Value of y after swap: 2

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

Without Using a Temporary Variable

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

x, y = y, x

So the above example can be modified to:

Example

# -*- coding: UTF-8 -*-
# Filename : test.py
# author by : www..com

# User input
x = input('Enter value for x: ')
y = input('Enter value for y: ')

# Swap without a temporary variable
x, y = y, x

print('Value of x after swap: {}'.format(x))
print('Value of y after swap: {}'.format(y))

Executing the above code produces the following output:

Enter value for x: 1
Enter value for y: 2
Value of x after swap: 2
Value of y after swap: 1

← Android ArchitecturePython3 Random Number β†’