Python Swap the Values of Two Variables
In Python, swapping the values of two variables can be done in several ways. The most common is to use a temporary variable to hold one of the values and then swap them. In addition, Python offers a more concise way: swapping values using tuple unpacking.
Method 1: use a temporary variable
Example
a
=
5
b
=
10
Swap using a temporary variable
temp
=
a
a
=
b
b
=
temp
(
"Value of a after swapping:"
,
a
)
(
"Value of b after swapping:"
,
b
)
Code analysis:
temp = a: Assign the value of the variableato the temporary variabletemp。a = b: Assign the value of the variablebAssign the value of to the variablea。b = temp: Assign the temporary variabletempAssign the value of to the variableb。- Finally, print the swapped
aandbvalue.
Output result:
交换后 a 的值: 10
交换后 b 的值: 5
Method 2: use tuple unpacking
The code:
Example
a
=
5
b
=
10
Swap using tuple unpacking
a
,
b
=
b
,
a
(
"Value of a after swapping:"
,
a
)
(
"Value of b after swapping:"
,
b
)
Code analysis:
a, b = b, a: This line packs the values ofbandainto a tuple and then unpacks them intoaandb, thereby performing the swap.- Finally, print the swapped
aandbvalue.
Output result:
交换后 a 的值: 10
交换后 b 的值: 5
Both methods can swap the values of two variables effectively, but tuple unpacking is more concise and Pythonic.
Python3 Examples