Unpack to a list

Is there any difference in Python between unpacking into a tuple:

x, y, z = v

and unpacking to a list?

[x, y, z] = v
+4
source share
2 answers

Absolutely nothing, right down to the bytecode (using dis):

>>> def list_assign(args):
    [x, y, z] = args
    return x, y, z

>>> def tuple_assign(args):
    x, y, z = args
    return x, y, z

>>> import dis
>>> dis.dis(list_assign)
  2           0 LOAD_FAST                0 (args) 
              3 UNPACK_SEQUENCE          3 
              6 STORE_FAST               1 (x) 
              9 STORE_FAST               2 (y) 
             12 STORE_FAST               3 (z) 

  3          15 LOAD_FAST                1 (x) 
             18 LOAD_FAST                2 (y) 
             21 LOAD_FAST                3 (z) 
             24 BUILD_TUPLE              3 
             27 RETURN_VALUE         
>>> dis.dis(tuple_assign)
  2           0 LOAD_FAST                0 (args) 
              3 UNPACK_SEQUENCE          3 
              6 STORE_FAST               1 (x) 
              9 STORE_FAST               2 (y) 
             12 STORE_FAST               3 (z) 

  3          15 LOAD_FAST                1 (x) 
             18 LOAD_FAST                2 (y) 
             21 LOAD_FAST                3 (z) 
             24 BUILD_TUPLE              3 
             27 RETURN_VALUE 
+10
source

No. In fact, it x, y, z = vis an abbreviation for:

(x, y, z) = v

... which is unpacked into a tuple. The same behavior occurs:

>>> v = (1, 3, 4)
>>> [x, y, z] = v
>>> x, y, z
(1, 3, 4)
>>> x, y, z = v
>>> x, y, z
(1, 3, 4)
+2
source

Source: https://habr.com/ru/post/1541780/


All Articles