Search code examples
pythonlistpython-3.xiterable-unpacking

Why can't list unpacking be used for indexing a second list?


… e.g. a[*b] where a and b are both lists and len(b) == 1

Using the simple example below:

a = [1,2,3,4]
b = [0]

a[*b]

Why does running the above raise an exception?

    a[*b]
      ^
SyntaxError: invalid syntax

Solution

  • Because that syntax is invalid.

    Iterable unpacking is allowed in various circumstances – for example:

    … but not universally, and definitely not for indexing. In fact, it's unclear what your proposed syntax even means. Consider: what would a[*b] return if b were [1, 2]?