Search code examples
pythonpython-3.xiterable-unpacking

Why is 'Extended Iterable Unpacking' not working for empty strings?


Why is

>>> a, *b = '' 

not possible, when

>>> a, *b = ' '
>>> a, b
(' ', [])  # b == empty list here anyway.

and

>>> type('')
<class 'str'>

I mean, why isn't it

>>> a, *b = ''
>>> a, b  # a could == ''
('', [])

Solution

  • Because there is one mandatory variable specified.

    The right side should have at least one item (one character for string).


    According to PEP-3131:

    A tuple (or list) on the left side of a simple assignment (unpacking is not defined for augmented assignment) may contain at most one expression prepended with a single asterisk (which is henceforth called a "starred" expression, while the other expressions in the list are called "mandatory"). This designates a subexpression that will be assigned a list of all items from the iterable being unpacked that are not assigned to any of the mandatory expressions, or an empty list if there are no such items.