Slicing a Numpy ndarray with indices stored in two lists

With A a Numpy ndarray, is there a generic way to implement this code in a single line and without testing the dimension of A (assumed equal to 2 or 3)?

if len(A.shape) == 2: B = A[st[0]:ed[0], st[1]:ed[1]]
else: B = A[st[0]:ed[0], st[1]:ed[1], st[2]:ed[2]]

First, you should write code in Discourse (and StackOverflow etc) in code blocks, eg

```python
if len(A.shape) == 2:
    B = A[st[0]:ed[0], st[1]:ed[1]]
else:
    B = A[st[0]:ed[0], st[1]:ed[1], st[2]:ed[2]]
```

Second, NumPy forums and StackOverflow are better places for this question.

Third, A.ndim is the same as len(A.shape).

Fourth, in answer to your question,

indices = no.stack([st, ed], axis=1)
B = A[tuple(slice(i, j) for i, j in indices[:A.ndim])]
1 Like

Thanks for your recommendations and the solution!