unpacking lists (there's more than one way to do it!)

Neal Norwitz neal at metaslash.com
Tue Jan 15 22:50:27 EST 2002


Roy Smith wrote:
> 
> All of the following seem to have the same effect:
> 
> x, y = list
> (x, y) = list
> [x, y] = list
> 
> Is there any reason to prefer one over the other?  FWIW, I tend to write
> the last because I think it looks cleaner.

>>> def x(y):
...   a, b = y
...   (a, b) = y
...   [a, b] = y
... 
>>> import dis
>>> dis.dis(x)
          0 SET_LINENO               1

          3 SET_LINENO               2
          6 LOAD_FAST                0 (y)
          9 UNPACK_SEQUENCE          2
         12 STORE_FAST               2 (a)
         15 STORE_FAST               1 (b)

         18 SET_LINENO               3
         21 LOAD_FAST                0 (y)
         24 UNPACK_SEQUENCE          2
         27 STORE_FAST               2 (a)
         30 STORE_FAST               1 (b)

         33 SET_LINENO               4
         36 LOAD_FAST                0 (y)
         39 UNPACK_SEQUENCE          2
         42 STORE_FAST               2 (a)
         45 STORE_FAST               1 (b)
         48 LOAD_CONST               0 (None)
         51 RETURN_VALUE        

They are all the same in Python 2.1, 2.2, and basically the same in 1.5.2.

Neal



More information about the Python-list mailing list