Basic Indexing and Slicing
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
This page was checked in October 2026 against NumPy 2.5 (2.5.4 is the latest patch release). Examples target Python 3.13 or 3.14 and were run on Python 3.13. Every example was run with NumPy 2.5.4, and the printed output is real. The behaviour described here is stable across NumPy 1.x and 2.x, but the copies and views page matters for several deprecations in 2.4 and 2.5 that touch indexing-related attributes.
NumPy distinguishes two families of indexing. Basic indexing uses integers, slices, Ellipsis and np.newaxis and always returns a view of the original data. Advanced indexing uses integer arrays, lists or boolean arrays and always returns a copy; it is covered in Advanced and Boolean Indexing. This page covers the first family. Knowing which family an expression belongs to is the single most useful indexing skill, because it decides whether an assignment or an in-place operation changes the original array.
The examples use this array, which has shape (4, 6):
import numpy as np
a = np.arange(24).reshape(4, 6)
print(a)
[[ 0 1 2 3 4 5] [ 6 7 8 9 10 11] [12 13 14 15 16 17] [18 19 20 21 22 23]]
Source: NumPy user guide: Basic indexing
Integer indexing
An integer selects one position along one axis and removes that axis from the result. Indexing is zero-based and negative integers count from the end, so -1 is the last element of an axis.
print(a[1, 2], a[1][2], a[-1, -1])
print(a[1]) # one integer on a 2-D array: a 1-D row
print(type(np.arange(5)[3]))
8 8 23 [ 6 7 8 9 10 11] <class 'numpy.int64'>
Two things to note. First, a[1, 2] and a[1][2] give the same value, but a[1][2] first builds an intermediate row view and then indexes it, so it is slower and, worse, breaks as soon as the first index is a slice or array. Write all indices inside one pair of brackets separated by commas. Second, indexing a single element returns a NumPy scalar such as numpy.int64, not a Python int. Use .item() when you need the Python object. On 64-bit Windows the default integer is also 64-bit since NumPy 2.0, so the printed type is the same on every platform.
When you give fewer indices than the array has axes, the missing trailing axes are taken in full: a[1] is the same as a[1, :].
Slices: start, stop and step
A slice start:stop:step selects a regular range along one axis and keeps that axis. The rules are the same as for Python lists:
-
startis inclusive and defaults to0(or to the last element whenstepis negative). -
stopis exclusive and defaults to the axis length (or to before the first element whenstepis negative). -
stepdefaults to1; a negative step walks backwards. -
Negative
startandstopcount from the end. -
Out-of-range slice bounds are clipped silently, unlike integer indices.
print(a[1:3, ::2]) # rows 1-2, every second column
print(a[::-1, 0]) # first column, rows reversed
print(a[0, 4:100].shape) # stop is clipped to the axis length
t = np.arange(10)
print(t[7:2:-2], t[:-8:-1])
[[ 6 8 10] [12 14 16]] [18 12 6 0] (2,) [7 5 3] [9 8 7 6 5 4 3]
The difference between an integer and a length-one slice is the most common source of shape surprises. An integer removes the axis, a slice keeps it:
print(a[1].shape, a[1:2].shape) # (6,) versus (1, 6)
print(a[:, 0].shape, a[:, 0:1].shape) # (4,) versus (4, 1)
Keeping the axis with 0:1 is often the simplest way to get a column vector without calling reshape. A step other than one is allowed and still produces a view, so a[::2, ::3] references the original memory with larger strides instead of copying. You can see this in the strides of the result:
s = a[::2, ::3]
print(s.shape, s.strides, a.strides)
(2, 2) (96, 24) (48, 8)
The result strides are the original strides multiplied by the steps. The memory layout and strides page explains why this works.
Ellipsis and np.newaxis
Ellipsis (written ...) stands for "as many full slices : as are needed to fill the remaining axes". It can appear once in an index and is invaluable for code that must work on arrays of any number of dimensions. np.newaxis is an alias of None; it inserts a new axis of length one at that position, which is the basis of broadcasting tricks such as turning a vector into a column.
x = np.arange(2 * 3 * 4).reshape(2, 3, 4)
print(x[..., 0].shape) # last axis fixed, same as x[:, :, 0]
print(x[0, ...].shape) # same as x[0]
print(x[:, np.newaxis].shape) # new axis inserted at position 1
print(a[:, None, 0].shape) # None is the same as np.newaxis
(2, 3) (3, 4) (2, 1, 3, 4) (4, 1)
Prefer the name np.newaxis in shared code, because None in an index is easy to read as a mistake. An index may mix integers, slices, Ellipsis and np.newaxis freely; they are all basic indexing and the result is still a view.
Assignment through slices
Because a basic index is a view, assigning to it writes into the original array. The right-hand side may be a scalar or any array that broadcasts to the shape of the selected region.
a[0] = 100 # scalar broadcast to a whole row
a[:, 0] = [1, 2, 3, 4] # one value per row
a[2:, 4:] = np.array([[7], [8]]) # shape (2, 1) broadcast to (2, 2)
print(a)
[[ 1 100 100 100 100 100] [ 2 7 8 9 10 11] [ 3 13 14 15 7 7] [ 4 19 20 21 8 8]]
The shape rules are those of broadcasting; a right-hand side that cannot broadcast raises ValueError. Assignment also casts the value to the array dtype, which can silently truncate: assigning 2.9 into an integer array stores 2. The related behaviour of out-of-range Python integers under NEP 50 is described in Type Promotion.
A view also reflects later writes to its base and the other way round:
b = np.arange(24).reshape(4, 6)
v = b[1:3, 1:3]
v[0, 0] = -1
print(b[1, 1], np.shares_memory(b, v), v.base is b)
-1 True False
The last value is False only because b is itself a view of the temporary arange buffer; in that case v.base is the array that owns the memory. Use np.shares_memory to test sharing instead of comparing .base. This is discussed in detail on the copies and views page.
Out-of-bounds indices
An integer index outside the axis raises IndexError; a slice never does.
try:
a[10, 0]
except IndexError as e:
print("IndexError:", e)
IndexError: index 10 is out of bounds for axis 0 with size 4
Using more indices than the array has dimensions also raises IndexError. Because slices clip silently, code such as a[:, 0:100] never fails even when the number is wrong, so validate the shape explicitly where it matters.
Index tuples and np.s_
An index expression is really a tuple. a[1, 2] is a[(1, 2)], and a[:, 0] is a[(slice(None), 0)]. This is how you build indices programmatically, for instance to apply the same slice to several arrays or to select an axis chosen at run time. np.s_ and np.index_exp build index objects with slice syntax.
print(a[(1, 2)], a[(slice(None), 0)])
print(np.s_[1:3, ..., 0])
print(np.index_exp[::2])
def take_axis(arr, i, axis):
idx = [slice(None)] * arr.ndim
idx[axis] = i
return arr[tuple(idx)]
8 [1 2 3 4] (slice(1, 3, None), Ellipsis, 0) (slice(None, None, 2),)
A list used as an index is not treated as a tuple any more: a[[1, 2]] is advanced indexing (rows 1 and 2), whereas a[(1, 2)] is a single element. Always convert a list of slices with tuple(...), as take_axis does above. A list that contains slices is rejected with IndexError in current NumPy, although older code relied on it behaving like a tuple.
Source: NumPy reference: numpy.s_
Common pitfalls
-
Mistaking a view for a copy.
sub = a[1:3]shares memory witha. Changingsubchangesa. Calla[1:3].copy()when you need independence. -
Holding on to a huge base. A small slice keeps the whole parent buffer alive. Copy small slices that outlive the large array.
-
Chained indexing for assignment.
a[1][2] = 5works only becausea[1]is a view; as soon as the first index is advanced,a[[1]][0] = 5writes into a temporary copy and is lost. Use one index expression:a[[1], 0] = 5. -
Integer versus slice shapes.
a[:, 0]is 1-D,a[:, 0:1]is 2-D. Broadcasting results depend on this. -
Negative steps are not copies.
a[::-1]is a view with a negative stride, which some C extensions andreshape(copy=False)cannot use. -
Setting
shapeorstridesdirectly. Assigning toarr.shapewas deprecated in NumPy 2.5 and assigning toarr.stridesin NumPy 2.4. Usereshapeandnp.lib.stride_tricks.as_stridedinstead.
Older tutorials and books
The core rules above have not changed since the earliest NumPy releases, so older material is largely correct on slicing. What does date a tutorial is what surrounds it.
| Statement in older sources | Status in NumPy 2.5 | Replacement |
|---|---|---|
Indexing with a list of slices, |
Raises |
|
|
|
Use 2-D |
Setting |
Deprecated in NumPy 2.5 |
|
Examples print |
The scalar repr is |
|
Related pages
-
Advanced and Boolean Indexing for integer-array and mask indexing, which copy.
-
Copies and Views for how to test and control sharing.
-
Broadcasting for the shape rules used in assignment.
-
The Absolute Basics and Array Creation for building the arrays used here.