The canonical way to swap two variables in Python is
a, b = b, a
Please note than this is valid whatever the "type" of a
or b
is (numeric, string, tuple, object, ...). Of course, it works too if both variables reference values of different types.
As many imperative languages, Python evaluates assignments right to left. Conceptually all behave like if a tuple was build for the right hand part of the expression, and then deconstructed to perform the affectation to the left hand part. This has already been explained more clearly than I can here: https://stackoverflow.com/a/14836456/2363712
The real details are implementation dependent though. For example, to build on a comment by @undefined is not a function below, the CPython virtual machine has a ROT_TWO opcode that swap the two top-level items on the stack, and so allow to optimize such affectation. See this previous answer for a detailed explanation: https://stackoverflow.com/a/21047622/2363712
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…