53

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?

1
  • 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. Commented Jul 28, 2014 at 16:39

1 Answer 1

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).

Sign up to request clarification or add additional context in comments.

2 Comments

"Which one is more pythonic?" -- I'd say the first option since it has less syntax and is more "readable."
@Kevin It's the same on Python 3.2, at least (that's all I have access to right now).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.