Python Swapping Variables
The following example takes two variables from user input and swaps them:
Example
-- coding: UTF-8 --
Filename : test.py
author by : www.runoob.com
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
(
'
After swapping, the value of x is: {}
'
.
format
(
x
)
)
(
'
After swapping, the value of y is: {}
'
.
format
(
y
)
)
The output of the code above is:
输入 x 值: 2
输入 y 值: 3
交换后 x 的值为: 3
交换后 y 的值为: 2
In the above example we create a temporary variable temp and store the value of x in temp, then assign the value of y to x, and finally assign temp to y.
Without a temporary variable
We can also swap variables without creating a temporary variable, using a very elegant approach:
x,y = y,x
So the above example can be modified to:
Example
-- coding: UTF-8 --
Filename : test.py
author by : www.runoob.com
User input
x
=
input
(
'
Enter the value of x:
'
)
y
=
input
(
'
Enter the value of y:
'
)
Without a temporary variable
x
,
y
=
y
,
x
(
'
After swapping, the value of x is: {}
'
.
format
(
x
)
)
(
'
After swapping, the value of y is: {}
'
.
format
(
y
)
)
The output of the code above is:
输入 x 值: 1
输入 y 值: 2
交换后 x 的值为: 2
交换后 y 的值为: 1
Python3 Examples