Python Swapping Values, How is it working internally?
This is the Python's famous elegant code for swapping variables without using a temporary variable.
|
|
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 anunpacking assignment
Unpacking
List unpacking
|
|
Dictionary unpacking
|
|
Hence, swapping the values can be written as following using list
|
|
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.