52

These three expressions seem to be equivalent:

a,b,c = line.split()
(a,b,c) = line.split()
[a,b,c] = line.split()

Do they compile to the same code?

Which one is more pythonic?

sds
  • 58,617
  • 29
  • 161
  • 278
  • 1
    You need some kind of grouping for `[[a]] = b`, e.g., and `((a,),) = b` doesn’t look particularly nice either. As for which one’s more readable when that’s not necessary, it’s up to you. – Ry- Jul 28 '14 at 16:39

1 Answers1

66

According to dis, they all get compiled to the same bytecode:

>>> def f1(line):
...  a,b,c = line.split()
... 
>>> def f2(line):
...  (a,b,c) = line.split()
... 
>>> def f3(line):
...  [a,b,c] = line.split()
... 
>>> import dis
>>> dis.dis(f1)
  2           0 LOAD_FAST                0 (line)
              3 LOAD_ATTR                0 (split)
              6 CALL_FUNCTION            0
              9 UNPACK_SEQUENCE          3
             12 STORE_FAST               1 (a)
             15 STORE_FAST               2 (b)
             18 STORE_FAST               3 (c)
             21 LOAD_CONST               0 (None)
             24 RETURN_VALUE        
>>> dis.dis(f2)
  2           0 LOAD_FAST                0 (line)
              3 LOAD_ATTR                0 (split)
              6 CALL_FUNCTION            0
              9 UNPACK_SEQUENCE          3
             12 STORE_FAST               1 (a)
             15 STORE_FAST               2 (b)
             18 STORE_FAST               3 (c)
             21 LOAD_CONST               0 (None)
             24 RETURN_VALUE        
>>> dis.dis(f3)
  2           0 LOAD_FAST                0 (line)
              3 LOAD_ATTR                0 (split)
              6 CALL_FUNCTION            0
              9 UNPACK_SEQUENCE          3
             12 STORE_FAST               1 (a)
             15 STORE_FAST               2 (b)
             18 STORE_FAST               3 (c)
             21 LOAD_CONST               0 (None)
             24 RETURN_VALUE        

So they should all have the same efficiency. As far as which is most Pythonic, it's somewhat down to opinion, but I would favor either the first or (to a lesser degree) the second option. Using the square brackets is confusing because it looks like you're creating a list (though it turns out you're not).

dano
  • 91,354
  • 19
  • 222
  • 219
  • 4
    "Which one is more pythonic?" -- I'd say the first option since it has less syntax and is more "readable." – Casey Falk Jul 28 '14 at 16:39
  • 1
    @Kevin It's the same on Python 3.2, at least (that's all I have access to right now). – dano Jul 28 '14 at 16:42