Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 14.2 — Indexing, Slicing and Reshaping Arrays
Python · Example 1 of 2

Indexing, slices, and views

Add print(grid) at the end: you will see that row 0 now starts with 99 because the slice was a view.

You pick elements out of an array with indices, slices, boolean masks and lists of positions. Slices are views that share memory with the original, and reshape changes the shape without changing the numbers.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

From x = np.arange(1, 11), print only the even numbers using a mask (x % 2 == 0).

02

From grid = np.arange(9).reshape(3, 3), print the middle row, the last column, and the 2-by-2 block in the top left corner.

03

Given a = np.array([5, 1, 4]), make b = a[:2].copy(), set b[0] = 0, and show that a did not change.

04

For a = np.arange(10), use np.shares_memory to show that a[6:] is a view but a[a > 5] is a copy. Then use a slice to set the last four elements of a to 0 and print a.

Explain it without notes

01

What is the difference between a view and a copy? Which indexing methods give each?

02

How do you select the elements of an array that satisfy two conditions? Why not use and?

03

What does reshape(-1, 2) do, and when does reshape fail?

04

For a (2, 3) array, what are the shapes of sum(axis=0) and sum(axis=1) and why?

05

A function receives an array, sets arr[0] = 0 and the caller's data changes unexpectedly. Why, and how do you design around it?

Indexing, slices, and views
Sign in to run this example in your browser.

Expected output

[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
row 1: [4 5 6 7]
cell [1, 2]: 6
column 0: [0 4 8]
block: [[1, 2], [5, 6]]
after changing the slice, original row 0: [99  1  2  3]
after changing a copy, original row 1: [4 5 6 7]
shares memory: True False