Python assignment destructuring

PythonDestructuring

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsdsView Question on Stackoverflow
Solution 1 - PythondanoView Answer on Stackoverflow