Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpacking into a list

Tags:

python

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

x, y, z = v

and unpacking into a list?

[x, y, z] = v
like image 667
Bach Avatar asked Dec 15 '22 22:12

Bach


1 Answers

Absolutely nothing, even 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 
like image 166
jonrsharpe Avatar answered Dec 17 '22 11:12

jonrsharpe