Search code examples
pythonpython-3.xiterable-unpacking

starred list variable swapping in python


I have a conceptual question. I have a few code snippets and their corresponding outputs

ls = [1,2,3,4]
a = '?'
a, *ls = *ls, a

a: 1 ls: [2, 3, 4, '?']

ls = [1,2,3,4]
a = '?'
a, *ls = ls, a

a: [1, 2, 3, 4] ls: ['?']

ls = [1,2,3,4]
a = '?'
a, ls = *ls, a

ValueError: too many values to unpack (expected 2)

The first one makes sense to me, but examples 2 and 3 leave me confused. Why are the outputs for the 2nd and 3rd example the way they are?


Solution

  • Example 1 assigns 5 elements (*ls, a). The first goes to the first variable and the rest to the starred variable (a, *ls).

    Example 2 assigns 2 elements (ls, a). The first element goes to the first variable and the rest (i.e. the other element) to the starred variable (a, *ls).

    Example 3 attempts to assign 5 elements (*ls, a) to exactly two variables. This would leave 3 values unassigned, so you get an error.