Python Swapping Values, How is it working internally?

This is the Python's famous elegant code for swapping variables without using a temporary variable.

1
2
3
4
5
6
  a = 10
  b = 5
  c = 1
  
  a,b,c = b,c,a
  

Have you ever wondered what makes this python to do this elegant and beautiful code? Lets breakdown little bit. At the end it is all an simple illusion and simplicity. You must have heard this one.

“one man's magic is another man's engineering”

Discussion:

Swapping
    a,b,c = b,c,a
 
  • Right hand side of the expression is a tuple. It is an immutable tuple of three values. Often, tuple is associated with parentheses, as in (b,c,a) but parentheses are not mandatory. Here packing of three values are made.
  • Left hand side of the expression is an assignment operator. Here, unpacking of the tuple is happening. Python lets you use several targets (variables, indexings, etc.), separated by commas, on an assignment’s lefthand side. Such a multiple assignment is also called an unpacking assignment
Unpacking
List unpacking
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
    # unpacking examples
    def date_display(day, month, year):
        return "{0}/{1}/{2}".format(day,month,year)
    
    # List 
    date = ["01","12", "1989"]
    # Here we didnt pass the each attribute
    # instead we used unpacking feature to pass the variable
    print(date_display(*date))
 
Dictionary unpacking
1
2
3
4
5
6
7
err = {"code":"VAL", "message": "validation error"}

def err_display(code,message):
    return "{code}:{message}".format(code=code,message=message)
# Here we used ** operator to unpack the dictionary
# and pass keyword argument to the function
print(err_display(**err))

Hence, swapping the values can be written as following using list

1
2
3
4
5
6
7
a = 10
b = 5
c = 1
print(a,b,c)
list = [b,c,a]
a,b,c = list
print(a,b,c)

Tuple packing, done using commas, and sequence unpacking, done by placing several comma-separated targets on the lefthand side of a statement, are enabling swapping of values without using temporary variables.