Python Swap Variables

Python3 Examples

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

Examples

# -*- coding: UTF-8 -*- # Filename : test.py # author by : www.example.com # User input x = input('Enter value for x:') y = input('Enter value for y:') # Create a temporary variable and swap temp = x x = y y = temp print('After swap, the value of x is: {}'.format(x)) print('After swap, the value of y is: {}'.format(y))

Executing the above code produces the following output:

输入 x 值: 2
输入 y 值: 3
交换后 x 的值为: 3
交换后 y 的值为: 2

In the above example, we created a temporary variable temp, 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 the variables without creating a temporary variable, using a very elegant approach:

x,y = y,x

So the above example can be modified as follows:

Example

# -*- coding: UTF-8 -*- # Filename : test.py # author by : www.example.com # User input x = input('Enter value for x:') y = input('Enter value for y:') # Without using a temporary variable x,y = y,x print('After swap, the value of x is: {}'.format(x)) print('After swap, the value of y is: {}'.format(y))

Executing the above code produces the following output:

输入 x 值: 1
输入 y 值: 2
交换后 x 的值为: 2
交换后 y 的值为: 1

Python3 Examples

Other Extensions