Exercises

These exercises check whether shape, dtype, axes, and slicing are becoming ordinary.

Exercise: Create and inspect

Edit the code so it prints the shape (2, 3).

Create a 2 by 3 array

Runs locally with Python in your browser.

Ready to run.

Hint

Use two inner lists. Each inner list should contain three numbers.

Solution

One fix is:

The array has two rows and three columns, so its shape is (2, 3).

Exercise: Column sums

Edit the code so it prints [5 7 9].

Sum each column

Runs locally with Python in your browser.

Ready to run.

Hint

Column sums use axis=0.

Solution

Use axis=0:

This sums down the rows:

[1 + 4, 2 + 5, 3 + 6] = [5, 7, 9]
Exercise: Select a row

Which expression selects the first row of A?

Answer it first, then check.

Hint

The first row is row index 0. Use : for all columns.

Solution

Use:

A[0, :]

The 0 selects the first row. The : keeps all columns.

Exercise: Copy before mutating

Edit the code so the output contains A: [[1 2 3] and row: [99 2 3].

Avoid changing the original

Runs locally with Python in your browser.

Ready to run.

Hint

Call .copy() on the slice:

row = A[0, :].copy()
Solution

Use .copy():

The row is separate, so changing it does not change A.

Exercise: Read an axis result

If A.shape is (4, 2), what is the shape of A.mean(axis=1)?

Answer it first, then check.

Hint

axis=1 reduces across columns and leaves one value per row.

Solution

The shape is:

(4,)

axis=1 removes the second axis. The result keeps one value for each of the four rows.