Syntax error when unpacking in NumPy arrays

149 views Asked by At

Why does the code below raise a SyntaxError on line 5 for Python 3.8, 3.9, and 3.10 (it seems fine for Python 3.11 and 3.12)?

import numpy as np

a = np.zeros(5)
new_dim = 3
a = a[:, *[np.newaxis] * new_dim]

Was it a bug in former versions of Python?

1

There are 1 answers

0
Tom M. Ragonneau On

Although star expressions in indexes have been introduced in Python 3.11, I just realized it is possible to do it in the following way.

import numpy as np

a = np.zeros(5)
new_dim = 3
a = a[(...,) + (np.newaxis,) * new_dim]