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?
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