Is there a standardized method to swap two variables in Python?
Solution 1:
Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side.
Python docs: Evaluation order
That means the following for the expression a,b = b,a
:
- The right-hand side
b,a
is evaluated, that is to say, a tuple of two elements is created in the memory. The two elements are the objects designated by the identifiersb
anda
, that were existing before the instruction is encountered during the execution of the program. - Just after the creation of this tuple, no assignment of this tuple object has still been made, but it doesn't matter, Python internally knows where it is.
- Then, the left-hand side is evaluated, that is to say, the tuple is assigned to the left-hand side.
- As the left-hand side is composed of two identifiers, the tuple is unpacked in order that the first identifier
a
be assigned to the first element of the tuple (which is the object that was formerly b before the swap because it had nameb
)
and the second identifierb
is assigned to the second element of the tuple (which is the object that was formerly a before the swap because its identifiers wasa
)
This mechanism has effectively swapped the objects assigned to the identifiers a
and b
So, to answer your question: YES, it's the standard way to swap two identifiers on two objects.
By the way, the objects are not variables, they are objects.
Solution 2:
That is the standard way to swap two variables, yes.
Solution 3:
I know three ways to swap variables, but a, b = b, a
is the simplest. There is
XOR (for integers)
x = x ^ y
y = y ^ x
x = x ^ y
Or concisely,
x ^= y
y ^= x
x ^= y
Temporary variable
w = x
x = y
y = w
del w
Tuple swap
x, y = y, x
Solution 4:
I would not say it is a standard way to swap because it will cause some unexpected errors.
nums[i], nums[nums[i] - 1] = nums[nums[i] - 1], nums[i]
nums[i]
will be modified first and then affect the second variable nums[nums[i] - 1]
.
Solution 5:
Does not work for multidimensional arrays, because references are used here.
import numpy as np
# swaps
data = np.random.random(2)
print(data)
data[0], data[1] = data[1], data[0]
print(data)
# does not swap
data = np.random.random((2, 2))
print(data)
data[0], data[1] = data[1], data[0]
print(data)
See also Swap slices of Numpy arrays