Home > other >  Updated Python Starred Expressions Error in Numpy Indexing
Updated Python Starred Expressions Error in Numpy Indexing

Time:12-10

I have some code that I have been running in Python 3.6, but when I move to Python 3.9 I recieve the below error:

SyntaxError: can't use starred expression here

I understand some syntax related to expressions of the form (*something) was implemented in 3.9 that is not backwards compatible (see, for example, here).

Here is a minimal working example of what my code tries to do:

# Get some data
y = np.random.randn(100,100,100)

# Indexes stored as a tuple
x = (1,2)

# Result I'm after
result = y[...,(*x)]

In the above example, I am trying to essentially return y[:,1,2], but in practice, my tuple may have more values, and my array may be larger.

The above code works fine in Python 3.6 but doesn't work in Python 3.9. I cannot work out what the equivalent piece of code would be in Python 3.9 and above. I don't want to assume the number of dimensions in Y (e.g. I want to keep the ...), but I want to retain the behaviour I have above. How can I do this?

CodePudding user response:

You were almost there:

result = y[(..., *x)]

Intermediate:

(..., *x)
# (Ellipsis, 1, 2)
  • Related