Search code examples
pythonpython-3.xassignment-operator

Understanding Python multiple assignment


Consider this assignment statement example:

>>> x, y = x[y] = {}, None
>>> x
{None: ({...}, None)}
>>> y
>>>

What is the value assigned to x and how does this assignment work?


Solution

  • The statement assigns the value on the far right to each target to its left, starting at the left. Thus, it's equivalent to

    t = {}, None
    x, y = t
    x[y] = t
    

    So, t starts out as a tuple consisting of an empty dict and the value None.

    Next, we unpack t and assign each part to x and y: x is bound to the empty dict, and y is bound to None.

    Finally, we can assign the tuple to x[y] as well, since we just defined x and y. The key None is added to the dict referenced by x, and its value is the original tuple. Thus, we've made x[y] refer to x itself: a cycle!

    Python can detect this cycle, so it shows the dict as {...}, rather than trying to expand it infinitely to {None: ({None: ({None: ....