How it works
A NumPy array applies an operation across every element at once, which is both faster and clearer than an explicit loop.
Express element-wise work as an operation on the whole array.
Common error
Writing a Python loop over an array, which discards the main reason for using one.
Worked example
These examples require NumPy or pandas, as shown by the imports.
Python
import numpy as np
a = np.array([1, 2, 3])
print((a * 2).tolist())
print((a + 10).tolist())Output
[2, 4, 6]
[11, 12, 13]NumPy array arithmetic applies elementwise under its broadcasting rules, unlike list repetition. Check shape and data type before assuming two arrays can be combined as intended.
Exercises
6.1.1 · Trace
Determine the exact output and explain the state changes.
Python
import numpy as np
a = np.array([2, 4, 6])
print(a[a > 3].tolist())Show solution
Output
[4, 6]The Boolean mask selects the entries whose values exceed 3.
6.1.2 · Write code
Use a NumPy array to square [2, 3, 4] elementwise and print an ordinary list.
Show solution
Exponentiation is elementwise for this array.
One valid solution
import numpy as np
a = np.array([2, 3, 4])
print((a ** 2).tolist())Expected output
[4, 9, 16]