Indexing and Slicing Arrays

Slices look like list slices and behave differently in one important way.

Indexing reads the same as a list

Positions from zero, negatives from the end, and a slice for a run of them.

import numpy as np

a = np.array([10, 20, 30, 40, 50])
print(a[0], a[-1])
print(a[1:4])

A slice is a view, not a copy

This is the difference that catches people. Writing into a slice of an array changes the original; the same line on a list would not. Use .copy() when you want your own.

import numpy as np

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

b = np.array([1, 2, 3])
safe = b[:2].copy()
safe[0] = 99
print(b)

Exercise

Try It Yourself

Write middle(values) that returns a list of everything except the first and last item.

Press Run to see output

Check Your Understanding