[Python-ideas] unpacking in index expression

Alexander Heger python at 2sn.net
Wed Apr 6 18:26:39 EDT 2016


I was trying to unpack an array or tuple in index expression (python
3.5.1) but this failed.
I think for consistency of language use it would be desirable to allow
that as well.  Below an example of my attempt indexing a numpy array,
x:

>>> import numpy as np
>>> x = np.arange(12).reshape(3,-1)
>>> x[*[0,1]]
    x[*[0,1]]
      ^
SyntaxError: invalid syntax

>>> x[*(0,1)]
    x[*(0,1)]
      ^
SyntaxError: invalid syntax

for the case of numpy, the latter works as intended w/o unpacking

>>> x[(0,1)]
 1

which is equivalent to the desired behaviour of unpacking

>>> x[0,1]
 1

but for the list case the behaviour is different (as intended by design)

>>> x[[0,1]]
array([[0, 1, 2, 3],
       [4, 5, 6, 7]])

My proposal hence is to allow unpacking in index expressions as well.
I do not have a use case for dictionary / keyword unpacking; this
would look awkward anyway.

-Alexander


More information about the Python-ideas mailing list