How to swap variables in Python 3 examples

In programming (and Python especially) swapping values of two variables is fundamental. Below you can find generic(and the python way) syntax:

a, b = b, a

For python especially is better to be used the first way: a, b = b, a or the tuple swap. The reason is: it's simple, easy to read and it's working fast. If you compare the both examples you will find that tuple swap (a, b = b, a) is much more clear and readable. From performance point of view is also much faster than usage of temporary variable. The other advantage of the tuple swapping is that you can use more than two variables for swap.

Example 1: Python swap variables by a, b = b, a or

You can see the first example below by using this syntax:

a, b = 1, 2
print(a, b)
 
a, b = b, a
print(a, b)

result:

1 2
2 1

Example 2: Python swap variables with temp variable

Another classic way and the only one possible for some languages is by using temporary variable. Below you can see the example:

temp = a
a = b
b = temp
del temp
print(a, b)

result:

1 2
2 1

Example 3: Python swap more than 2 variables

Another classic way and the only one possible for some languages is by using temporary variable. Below you can see the example:

a, b, c = 1, 2, 3
print(a, b, c)

a, b, c  = c, b, a
print(a, b, c)

result:

1 2 3
3 2 1

Finally I wanted to mention about the Evaluation order because is related to the first example: a, b, c = c, b, a.

Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side.

In the following lines, expressions will be evaluated in the arithmetic order of their suffixes:

expr1, expr2, expr3, expr4
(expr1, expr2, expr3, expr4)
{expr1: expr2, expr3: expr4}
expr1 + expr2 * (expr3 - expr4)
expr1(expr2, expr3, *expr4, **expr5)
expr3, expr4 = expr1, expr2

The main idea to get from this code example and explanation is:

You can use tuple swap values for any objects efficiently by using: a, b = b, a