You can create a mask over the elements in a that are within the given ranges and use this mask whenever you need to operate on a. If you want the encapsulate the mask and array in one entity, have a look at the numpy.ma module.

a = np.array([[[0,1,2],[3,4,5]],
             [[6,7,8],[9,10,11]]])

b = np.array([[1,2],
              [0,0]])

mask = np.arange(3)[None,None,:] <= b[:,:,None]

a[mask]

Output:

array([0, 1, 3, 4, 5, 6, 9])

But if you want the output as a non-homogeneous array, I cannot think of a better way to do that than using loops.

Answer from Kevin on Stack Overflow
🌐
Python.org
discuss.python.org › python help
Slicing question - Python Help - Discussions on Python.org
February 4, 2025 - Hei, I am trying to understand the difference between the following two code snippets (and it might be a numpy issue, please let me know): Using this code, I get the expected output: import numpy as np aa = np.arange(…
Discussions

How do I broadcast/slice by reference several indices for numpy arrays?
You'll need to use actual slicing: w12 = q[..., 1:3] There's two types of indexing in NumPy. Basic indexing is when you use only single integers or slice objects (like 1:3) as indices, and that will return a view into the original array. Then there's advanced indexing using arrays/lists of integers or booleans (like [1, 2]), which returns a copy. Documentation: https://numpy.org/devdocs/user/basics.indexing.html#basic-indexing https://numpy.org/devdocs/user/basics.indexing.html#advanced-indexing More on reddit.com
🌐 r/learnpython
4
0
February 13, 2022
Slicing arrays with a Colon via PythonCall
This works in Julia julia> rand(3,5)[:, ... np.random.rand(3,5)[:, 1] ERROR: Python: IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices Python stacktrace: none Stacktrace: [1] pythrow() @ PythonCall.Core ... More on discourse.julialang.org
🌐 discourse.julialang.org
3
0
June 3, 2024
Support for Multidimensional Slicing (Numpy Issue)
And here I once thought Python's slicing notation was beautiful and convenient. More on github.com
🌐 github.com
19
March 20, 2014
slice - How slicing in Python works - Stack Overflow
How does Python's slice notation work? That is: when I write code like a[x:y:z], a[:], a[::2] etc., how can I understand which elements end up in the slice? See Why are slice and range upper-bound More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 1
2

First of all, it will be hard to proceed with certainty without "actually running baseline tests". Because your dilemma can be summarized, as follows:

readability and convenience vs. performance and efficiency

While readability, convenience, and maintainability of the code are very important, the heavy computations still have to be done efficiently and use as much of the computational power as possible. Arrays are very special in that regard because they are stored contiguously in memory (column- or row-wise); thus, if one accesses them in the order they are stored, it minimizes the amount of cache misses, improving the usage of the CPU. Moreover, the vectorization instructions can be applied easier (depends on the compiler and its settings).

Now, with the introduction of slicing the array, excessive using strides, one will definitely sacrifice some efficiency. How much? Depends on the heaviness of the array computations, surrounding logic, basic quality of the other code, compiler, CPU, RAM etc. So, actual benchmarking is important to make a decision on how to organize the data-flow.

The picture below (IT Hare) has much more information, but you might look into the difference between the time required for L1-, L2-, L3-, RAM-read. By introducing non-contiguous access to your array, you will increase the amount of time your code will have to do L2-read instead of L1 and L3 instead of L2. Or if your arrays are very large and access is completely random, most reads will be performed from RAM every time, which is horrendous.

🌐
Reddit
reddit.com › r/learnpython › how do i broadcast/slice by reference several indices for numpy arrays?
r/learnpython on Reddit: How do I broadcast/slice by reference several indices for numpy arrays?
February 13, 2022 -
import numpy as np

q = np.reshape(np.arange(9), (3,3))

w0 = q[..., 0]
print(w0) #[0 3 6]
w0[...] = -1
print((q[..., 0] == (-1)*np.ones(3)).all()) #True as expected

w12 = q[..., [1,2]]
print(w12) #[[1 2] [3 5] [7 8]]
w12[...] = 0
print((q[..., [1,2]] == np.zeros((3,2))).all()) #False, not expected

print(q) #[[-1 1 2] [-1 3 5] [-1 7 8]]

q is a 3x3 array, w0 represents its first column and accesses q by reference. w12 represents q's second and third columns but is defined by copy. How can I broadcast/slice q in such a way that manipulating w12 manipulates q, too?

🌐
Julia Programming Language
discourse.julialang.org › general usage
Slicing arrays with a Colon via PythonCall - General Usage - Julia Programming Language
June 3, 2024 - This works in Julia julia> rand(3,5)[:, 1] and this works in Python >>> import numpy as np >>> np.random.rand(3,5)[:, 1] but this doesn’t work with PythonCall julia> using PythonCall julia> np = pyimport("numpy") julia> np.random.rand(3,5)[:, 1] ERROR: Python: IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices Python stacktrace: none Stacktrace: [1] pythrow() @ PythonCall.Core ~/.julia/packages/PythonCall/S5M...
🌐
GitHub
github.com › hylang › hy › issues › 541
Support for Multidimensional Slicing (Numpy Issue) · Issue #541 · hylang/hy
March 20, 2014 - Numpy has support for multidimensional arrays like so: >>> x = numpy.array([[x for x in range(10)] for y in range(10)]) >>> x[1:5,::2] array([[0, 2, 4, 6, 8], [0, 2, 4, 6, 8], [0, 2, 4, 6, 8], [0, 2, 4, 6, 8]]) It's a beautiful way of ha...
Author: hylang
Find elsewhere
🌐
W3Schools
w3schools.com › python › numpy › numpy_array_slicing.asp
NumPy Array Slicing
Slicing in python means taking elements from one given index to another given index. We pass slice instead of index like this: [start:end]. We can also define the step, like this: [start:end:step]. ... Note: The result includes the start index, ...
🌐
Stack Overflow
stackoverflow.com › questions › 509211 › how-slicing-in-python-works
slice - How slicing in Python works - Stack Overflow
How does Python's slice notation work? That is: when I write code like a[x:y:z], a[:], a[::2] etc., how can I understand which elements end up in the slice? See Why are slice and range upper-bound
🌐
Pythonhealthdatascience
pythonhealthdatascience.com › content › 01_algorithms › 03_numpy › 03_slicing.html
Array slicing and indexing — Python for health data science.
Going back to slicing we can understand the dimensions. Here’s a reminder fo the full array: ... Task: slice td so that we have the vector [13, 23, 33] i.e. the [i, 1, 0] elements where i is the row.
🌐
Swift Forums
forums.swift.org › evolution › discussion
Proposal: Python's indexing and slicing - Discussion - Swift Forums
December 18, 2015 - Examples: l=[1,2,3,4,5] l[-1] 5 l[-2] 4 l[2:4] [3, 4] l[2:] [3, 4, 5] l[-2:] [4, 5] l[:3] [1, 2, 3] l[::2] [1, 3, 5] l[::] [1, 2, 3, 4, 5]
🌐
Reddit
reddit.com › r/learnpython › problems with slicing 2d array
r/learnpython on Reddit: Problems with slicing 2D array
December 8, 2022 -

Hi, I'm trying to create a simple game of life and I have problems putting zeros on the edge of my grid. When i try the following code i get an error and I don't understand why.

the variable grid represent a 2D array.

the code:

grid[0,:] = np.zeros_like(grid[0,:])#top_row

grid[-1,:] = np.zeros_like(grid[-1,:])#bottom_row

grid[:,0] = np.zeros_like(grid[:,0])#left

grid[:,-1] = np.zeros_like(grid[:,-1])#right

the error:

TypeError: list indices must be integers or slices, not tuple

🌐
freeCodeCamp
freecodecamp.org › news › python-slicing-how-to-slice-an-array
Python Slicing – How to Slice an Array and What Does [::-1] Mean?
December 8, 2022 - It's also worth noting that the slicing action does not affect the original array. With slicing, you only "copy a portion" of the original array. For example, if you want to slice an array from a specific start value to the end of the array, here's how:
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-slicing-multi-dimensional-arrays
Python Slicing Multi-Dimensional Arrays - GeeksforGeeks
July 1, 2026 - This produces a new 2-D array containing the last column values from every matrix. Slices can be used not only for reading data but also for updating multiple values at once. Python · import numpy as np matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) matrix[0:2, 0:2] = 0 print(matrix) Output ·
🌐
DataCamp
datacamp.com › doc › numpy › array-slicing
NumPy Array Slicing
Array slicing is utilized when ... slicing syntax follows the format array[start:stop:step], where start is the index to begin the slice, stop is the index to end the slice (exclusive), and step defines the interval between elements....
🌐
The Python Coding Stack
thepythoncodingstack.com › notes from the near future › a slicing story
A Slicing Story - The Python Coding Stack
September 24, 2023 - Now, let's replicate these steps using NumPy arrays. You'll need to install NumPy using pip install numpy or your favourite package manager: The behaviour when you slice a NumPy array is different to the case when you slice a list. When you assign a new value to an item in subset_of_numbers_array, the original array also changes.
🌐
Nanyang Technological University
libguides.ntu.edu.sg › python › arrayslicing
NP.4 Array Slicing - Python for Basic Data Analysis - LibGuides at Nanyang Technological University
August 26, 2026 - Array slicing is similar to list slicing in Python. Array indexing also begins from 0. However, since arrays can be multidimensional, we have to specify the slice for each dimension. As we are mainly working with 2 dimensional arrays in this guide, we need to specify the row and column like ...
🌐
YouTube
youtube.com › watch
Slicing in NumPy is easy! ✂️ - YouTube
#coding #numpy #python Slicing in NumPy allows you to extract portions of an array using a [start:stop:step] syntax. It works similarly to Python lists but ...
Published: July 27, 2025
🌐
NumPy
numpy.org › doc › stable › user › basics.indexing.html
Indexing on ndarrays — NumPy v2.5 Manual
You may use slicing to set values in the array, but (unlike lists) you can never grow the array. The size of the value to be set in x[obj] = value must be (broadcastable to) the same shape as x[obj]. A slicing tuple can always be constructed as obj and used in the x[obj] notation.
🌐
YouTube
youtube.com › deeecode the web
How to Slice an Array in Python, with examples - YouTube
In this video, I simplify how to slice an array using different examples that shows the different ways arrays can be sliced in Python.Timestamp:00:00 Making ...
Published: December 9, 2022
Views: 328