In Python, I've seen two variable values swapped using this syntax:
left, right = right, left
Is this considered the standard way to swap two variable values or is there some other means by which two variables are by convention most usually swapped?
Swap using Bitwise XOR Operator This method is also known as XOR swap. XOR mean exclusive OR. We take two bits as inputs to the XOR in this bitwise operation. To get one output from XOR, only one input must be 1.
A simple swap function in Python is generally considered a function that takes two initialized variables, a = val_a and b = val_b , and returns a result of a = val_b and b = val_a . The function accepts variables of arbitrary types, or more precisely, variables that are assigned with objects of arbitrary types.
The bitwise XOR operator can be used to swap two variables. The XOR of two numbers x and y returns a number that has all the bits as 1 wherever bits of x and y differ. For example, XOR of 10 (In Binary 1010) and 5 (In Binary 0101) is 1111, and XOR of 7 (0111) and 5 (0101) is (0010).
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
:
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 identifiers b
and a
, that were existing before the instruction is encountered during the execution of the program.a
be assigned to the first element of the tuple (which is the object that was formerly b before the swap because it had name b
)b
is assigned to the second element of the tuple (which is the object that was formerly a before the swap because its identifiers was a
)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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With