Python Exchange Lists

In python, when I assign a list to another, for example:

a = [1,2,3] b = a 

Now b and point to the same list. Now, looking at the two lists,

 a = [1,2,3] b = [4,5,6] a,b = b,a 

Now, how do they exchange, like any other data type, and do not end both pointers to the same list?

+7
python list iterable-unpacking python-internals
source share
3 answers

Python seems to internally collapse elements. Check out this program.

 a, b = [1, 2], [2, 3] def func(): a, b = b, a import dis dis.dis(func) 

Exit

  4 0 LOAD_FAST 0 (b) 3 LOAD_FAST 1 (a) 6 ROT_TWO 7 STORE_FAST 1 (a) 10 STORE_FAST 0 (b) 13 LOAD_CONST 0 (None) 16 RETURN_VALUE 

So Python pushes links from b and a to the stack with LOAD_FAST . So now the topmost element is the link indicated by a , and the next is the link indicated by b . He then uses ROT_TWO to replace the top two elements of the stack. So now the topmost element is the link indicated by b , and the next is the link indicated by a , and then sets the top two elements of the stack to the values a and b respectively, with STORE_FAST .

How sorting occurs in an assignment statement when the number of elements we deal with is less than 4.

If the number of elements is greater than or equal to four , it creates a tuple and unpacks the values. Check out this program.

 a, b, c, d = [1, 2], [2, 3], [4, 5], [5, 6] def func(): a, b, c, d = d, c, b, a import dis dis.dis(func) 

Exit

  4 0 LOAD_FAST 0 (d) 3 LOAD_FAST 1 (c) 6 LOAD_FAST 2 (b) 9 LOAD_FAST 3 (a) 12 BUILD_TUPLE 4 15 UNPACK_SEQUENCE 4 18 STORE_FAST 3 (a) 21 STORE_FAST 2 (b) 24 STORE_FAST 1 (c) 27 STORE_FAST 0 (d) 30 LOAD_CONST 0 (None) 33 RETURN_VALUE 
+5
source share

Since the Python assignment first evaluates the right-handed expression, then applies the result to the left targets.

So, first Python creates (<reference to list b>, <reference to list a>) as a tuple, then assigns the first element in this tuple a , and the second element in this tuple - b . This neatly changes the links.

You can expand the assignment to read it as follows:

 tmp = b, a a = tmp[0] b = tmp[1] 
+3
source share

Now, how do they exchange, like any other data type, and do not end both pointers to the same list?

Since the moment you unpack the tuple b, a into the tuple a, b , you will lose references to the original a and b , and they will be reassigned.

0
source share

All Articles