In Python, you can swap variables after they have already been assigned objects. Below, we first assign
20 to the variable x and 30 to the variable y, and then swap them: x becomes 30, and y becomes 20. This method is called tuple packing/unpacking.x, y = 20, 30
x, y = y, x
print('x is: ', x)
print('y is: ', y)
x is 30
y is 20You can also use the XOR (exclusive or) operator to swap variables. This is a three-step method. In the example below, we swap the values of
x and y.x = 20
y = 30
# step one
x ^= y
# step two
y ^= x
# step three
x ^= y
print(f'x is: {x}')
print(f'y is: {y}')
x is: 30
y is: 20You can also use arithmetic operations (addition and subtraction) to swap variables without a temporary variable. However, this method is recommended for swapping numeric data types. Here's an example:
# Use arithmetic operations
x = 5
y = 10
x = x + y
y = x - y
x = x - y
print("After swapping:")
print("x =", x)
print("y =", y)
After swapping:
x = 10
y = 5As a result of these arithmetic operations, the values of
x and y have actually been swapped. After the swap, x contains the original value of y (10), and y contains the original value of x (5).This method of swapping variables without a temporary variable is based on the fact that when you add or subtract the value of one variable from another, you can effectively swap their values without the need for additional storage.
👉 https://t.me/DataScience4