get the i-th slice of the k-th dimension in a numpy array

b = a[(slice(None),) * k + (i,)]

Construct the indexing tuple manually.

As documented in the Python language reference, an expression of the form

a[:, :, :, :, :, i]

is converted to

a[(slice(None), slice(None), slice(None), slice(None), slice(None), i)]

We can achieve the same effect by building that tuple directly instead of using slicing notation. (There’s the minor caveat that building the tuple directly produces a[(i,)] instead of a[i] for k=0, but NumPy handles these the same for scalar i.)

Leave a Comment