pythonpython-3.xunpack

Don't understand why unpacking is not working as expected


Python unpacking not working

a = [1,2,3,4]
*m = a; //error

b,*m = a
print(m) //working

Please explain why the former one not working.


Solution

  • Per PEP-3132, which introduced this "extended iterable unpacking" syntax, and the language reference, the "starred" target is only valid in an assignment where the target is an iterable.

    It is also an error to use the starred expression as a lone assignment target, as in

    *a = range(5)
    

    This, however, is valid syntax:

    *a, = range(5)
    

    So to make that syntactically valid, you could do:

    *m, = a
    

    or even:

    [*m] = a
    

    Note, though, that the idiomatic way to create a shallow copy of a list is with a slice:

    m = a[:]