In python, when I assign a list to another, like:
a = [1,2,3]
b = a
Now b and a point to the same list. Now considering two lists,
a = [1,2,3]
b = [4,5,6]
a,b = b,a
Now how is it that they are swapped like any other data type and does not end up both pointing to the same list?
Because Python assignment first evaluates the right-hand-side expression, then applies the result to the left-hand-side targets.
So, first, Python creates
(<reference to list b>, <reference to list a>)
as a tuple, then assigns the first item in that tuple toa
, and the second item in that tuple tob
. This swaps the references around neatly.You could expand the assignment to read it like this:
Looks like Python internally swaps the items. Check this program
Output
So, Python pushes references from
b
anda
in the stack withLOAD_FAST
. So, now the top most element is the reference pointed bya
and the next one is the reference pointed byb
. Then it usesROT_TWO
to swap the top two elements of the stack. So, now, the top most element is the reference pointed byb
and the next one is the reference pointed bya
and then assigns the top two elements of the stack toa
andb
respectively withSTORE_FAST
.That's how sorting is happening in the assignment statement, when the number of items we deal with is lesser than 4.
If the number of items is greater than or equal to four, it builds a tuple and unpacks the values. Check this program
Output
Because the moment you unpack the tuple
b, a
into the tuplea, b
you loose references to the originala
andb
and they get re-assigned.