Skip to main content
MahiDev — Learn. Build. Become AI-ready.

Lesson 06

Slicing

Slice ranges of values from 1-D, 2-D, and 3-D arrays with begin, end, and step, including reversed steps and whole rows or columns.

Intermediate25 min
Slicing hero Module 23 Lesson 6

Slicing gets a range of values. Each dimension takes begin:end:step. end is left out of the result. Leave begin or end blank to run to the edge. Separate dimensions with commas.

A 3 by 4 array with a 2 by 2 block selected by slicing

1-D slices

With a positive step, NumPy moves forward from begin to end - 1. With a negative step, it moves backward from begin to end + 1. If the direction and the indices do not agree, the result is an empty array.

python
import numpy as np

a = np.array([10, 20, 30, 40, 50, 60, 70])
print(a[2:5])
print(a[:3])
print(a[4:])
print(a[::2])
print(a[::-1])
print(a[5:1:-1])
print(a[4:2])

Output:

text
[30 40 50]
[10 20 30]
[50 60 70]
[10 30 50 70]
[70 60 50 40 30 20 10]
[60 50 40 30]
[]

2-D slices

Write m[rows, cols], where each part is a slice or an index. A single : means all of that dimension, so m[:, 0] is the first column and m[1, :] is the second row.

python
import numpy as np

m = np.array([[11, 12, 13, 14],
              [21, 22, 23, 24],
              [31, 32, 33, 34]])
print(m[0:2, 1:3])
print(m[:, 0])
print(m[1, :])
print(m[::2, ::-1])

Output:

text
[[12 13]
 [22 23]]
[11 21 31]
[21 22 23 24]
[[14 13 12 11]
 [34 33 32 31]]

3-D slices

Add one more part for the blocks: t[blocks, rows, cols].

python
import numpy as np

t = np.arange(1, 19).reshape(2, 3, 3)
print(t[:, 0, :])
print(t[1, 1:, 1:])

Output:

text
[[ 1  2  3]
 [10 11 12]]
[[14 15]
 [17 18]]

A slice shares data

A slice is a view of the same values, not a copy. Changing the slice changes the original array. Call .copy() when you want an independent array. The next two lessons return to this.

python
import numpy as np

a = np.array([1, 2, 3, 4, 5])
part = a[1:4]
part[0] = 99
print(a)

safe = a[1:4].copy()
safe[0] = -1
print(a)

Output:

text
[ 1 99  3  4  5]
[ 1 99  3  4  5]

Key takeaways

  • begin:end:step leaves end out

  • a[::-1] reverses an array

  • m[:, 0] is a column, m[0, :] is a row

  • A slice is a view. Use .copy() for an independent array

  • Next: Advanced Indexing

  • Previous: Indexing

Loading playground…

Check your understanding

Slicing Quiz

What does a[2:5] include?

1 / 10