Bach
Bach

Reputation: 6217

Unpacking into a list

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

x, y, z = v

and unpacking into a list?

[x, y, z] = v

Upvotes: 4

Views: 165

Answers (2)

jonrsharpe
jonrsharpe

Reputation: 121987

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 

Upvotes: 10

Maxime Lorant
Maxime Lorant

Reputation: 36151

No. In fact the x, y, z = v is a shorthand for:

(x, y, z) = v

... which is unpacking in a tuple. The same behavior happens:

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

Upvotes: 2

Related Questions