Skip to main content

How to Take the First Rows of a NumPy Array with Slicing

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

A two-dimensional NumPy array is a grid of rows and columns, and a slice takes a block of it, such as its first two rows. It's the same start:stop slicing as Python lists, applied to rows. This guide takes the first two rows of a small grid, with real output from NumPy 2.5.5.

Syntax​

Syntax
<array>[:<number of rows>]
<array>[<start>:<stop>, <start>:<stop>] # rows, then columns
PartWhat it means
:<number of rows>The rows from the first up to, not including, that position
<start>:<stop>, <start>:<stop>A slice of rows, then a slice of columns. Left empty, a part means all of them

The NumPy indexing guide: "Basic slicing extends Python's basic concept of slicing to N dimensions."

Prerequisites​

  • NumPy in your project, for example with uv add numpy. This guide uses NumPy 2.5.5 on Python 3.15.2.

Step 1: Write the Script​

first_two_rows.py
import numpy as np

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

print(grid[:2])

The first_two_rows.py script in a macOS-style code window: a grid array of four rows of three numbers, and print(grid[:2]).

Step 2: Run It​

Terminal
uv run python first_two_rows.py
Output
[[1 2 3]
[4 5 6]]

The script's output in a terminal: the first two rows, [[1 2 3] and [4 5 6]].

The slice kept rows 0 and 1, all three columns each.

Common Mistakes​

MistakeWhat happensDo this instead
Changing a slice and expecting the original to stayA slice shares its data: setting top[0, 0] = 100 on grid[:1] changed grid to start with 100Copy it first: after grid[:1].copy() was changed, grid[0, 0] stayed 100, untouched by the copy
Expecting an error for a slice past the endgrid[:10] on two rows returned both rows, without an errorCheck the shape with grid.shape when the count matters

Troubleshooting​

SymptomLikely causeFix
The original array changed after you edited a sliceSlices are views of the same dataUse .copy() on the slice before changing it

FAQ​

How do I take columns as well?​

Add a second slice after a comma: grid[:, :2] gave the first two columns of every row, [[1 2] and [4 5]] for a two-row grid.

Why does a slice share the original's data?​

The guide: "All arrays generated by basic slicing are always views of the original array." A view is a new way of looking at the same numbers, not a second set of them.

Conclusion​

grid[:2] took the first two rows of the grid. A slice is a view of the same data, so .copy() it before you change it.

Additional Resources​