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?
Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side.
http://docs.python.org/3/reference/expressions.html#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 element are the objects designated by the identifiers b
and a
, that were existing before the instruction is encoutered during an execution of programa
be assigned to the first element of the tuple (which is the object that was formely 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.