Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 14.1 — NumPy Arrays
Python · Example 2 of 2

Element-wise maths, and one type for all

Compare the first two lines: the same * means repeat for a list and multiply for an array. For a realistic use, think of a shop's price list: one line, arr * 1.18, adds 18% tax to every price at once.

A NumPy array (ndarray) is a grid of numbers that all share one type, stored side by side in memory. Because of that, maths on a whole array runs in fast compiled code instead of a slow Python loop.

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

Create an array of the numbers 0, 5, 10, ..., 50 using np.arange, and print its shape and size.

02

Make a (3, 2) array of ones, multiply it by 7, and print it and its shape.

03

Given celsius = np.array([0.0, 37.0, 100.0]), compute the Fahrenheit values with one expression (c * 9 / 5 + 32).

Explain it without notes

01

What is the difference between a Python list and a NumPy array?

02

What do shape, ndim and dtype tell you? Give the values for np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]).

03

Why is a NumPy array faster than a loop over a list for maths?

04

What happens when you put ints, floats and strings in one array? Why does that matter?

05

A learner's integer total comes out negative in the browser but correct on their laptop, with no error. What happened and how do you prevent it?

Element-wise maths, and one type for all
Sign in to run this example in your browser.

Expected output

list * 2   : [30.0, 12.5, 8.0, 99.0, 30.0, 12.5, 8.0, 99.0]
array * 2  : [ 60.  25.  16. 198.]
array + 1  : [ 31.   13.5   9.  100. ]
array ** 2 : [ 900.    156.25   64.   9801.  ]
a + b: [11. 22. 33.]
a * b: [10. 40. 90.]
a > 1.5: [False  True  True]
mixed dtype: float64
text array: ['1' 'a'] U
int8 small: -56
float32 : 0.3
float64 : 0.30000000000000004