Search code examples
pythoniterable-unpacking

Python unpacking gotcha (unexpected behavior)


Can anybody explain what's going on here? Why does this happen?

>>> b = "1984"
>>> a = b, c = "AB"
>>> print(a, b, c)
'AB', 'A', 'B'

This behavior really blows my mind. Found this here


Solution

  • Such a cool question! Makes a lot of fun! :) Can be used at interviews :)

    Ok, here we are

    >>> b = "1984"
    >>> a = b, c = "AB"
    >>> print((a,b,c))
    ('AB', 'A', 'B')
    >>> a = (b, c) = "AB"
    >>> print((a,b,c))
    ('AB', 'A', 'B')
    >>>
    

    In python for multiple assignments, you can omit (...) and it looks like python parses this line similar to 2 lines

    a = "AB"
    b, c = "AB" # which is equal to (b, c) = "AB"
    

    Some more examples

    >>> a = b, c = "AB"
    >>> print((a,b,c))
    ('AB', 'A', 'B')
    >>> a = (b, c) = "AB"
    >>> print((a,b,c))
    ('AB', 'A', 'B')
    >>> a = "AB"
    >>> b, c = "AB"
    >>> print((a,b,c))
    ('AB', 'A', 'B')
    >>>
    

    It works using lists a well :)

    >>> a = [b, c] = 'AB'
    >>> print((a,b,c))
    ('AB', 'A', 'B')
    >>>
    

    Some more examples: