Search code examples
pythonvariable-assignment

Multiple assignment semantics


In Python one can do:

a, b   = 1, 2
(a, b) = 1, 2
[a, b] = 1, 2

I checked the generated bytecode using dis and they are identical.
So why allow this at all? Would I ever need one of these instead of the others?


See also Multiple assignment and evaluation order in Python regarding the basic semantics of this kind of assignment.

See also Understand Python swapping: why is a, b = b, a not always equivalent to b, a = a, b? for more complex cases, where the order of assignment matters.


Solution

  • One case when you need to include more structure on the left hand side of the assignment is when you're asking Python unpack a slightly more complicated sequence. E.g.:

    # Works
    >>> a, (b, c) = [1, [2, 3]]
    
    # Does not work
    >>> a, b, c = [1, [2, 3]]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: need more than 2 values to unpack
    

    This has proved useful for me in the past, for example, when using enumerate to iterate over a sequence of 2-tuples. Something like:

    >>> d = { 'a': 'x', 'b': 'y', 'c': 'z' }
    >>> for i, (key, value) in enumerate(d.iteritems()):
    ...     print (i, key, value)
    (0, 'a', 'x')
    (1, 'c', 'z')
    (2, 'b', 'y')