Python Swap Two Variables
In Python, swapping the values of two variables can be implemented in multiple ways. The most common method is to use a temporary variable to store the value of one variable, and then perform the swap. In addition, Python also provides a more concise way, namely using tuple unpacking to swap the values of variables.
Method 1: Using a temporary variable
Example
a = 5
b = 10
# Swap using a temporary variable
temp = a
a = b
b = temp
print("The value of a after swapping:", a)
print("The value of b after swapping:", b)
b = 10
# Swap using a temporary variable
temp = a
a = b
b = temp
print("The value of a after swapping:", a)
print("The value of b after swapping:", b)
Code explanation:
temp = a: Assign the variablea's value to the temporary variabletemp。a = b: Assign the variableb's value to the variablea。b = temp: Assign the temporary variabletemp's value to the variableb。- Finally, print the swapped
aandbvalues.
Output result:
交换后 a 的值: 10 交换后 b 的值: 5
Method 2: Using tuple unpacking
Code section:
Example
a = 5
b = 10
# Swap using tuple unpacking
a, b = b, a
print("The value of a after swapping:", a)
print("The value of b after swapping:", b)
b = 10
# Swap using tuple unpacking
a, b = b, a
print("The value of a after swapping:", a)
print("The value of b after swapping:", b)
Code explanation:
a, b = b, a: This line of code packsbandathe values into a tuple, then unpacks and assigns them toaandb, thereby achieving the swap.- Finally, print the swapped
aandbvalues.
Output result:
交换后 a 的值: 10 交换后 b 的值: 5
Both of these methods can effectively swap the values of two variables, but the tuple unpacking approach is more concise and Pythonic.
Other Extensions
Python3 Examples