Elementwise Math
Add Arrays
Two 6-element lists summed position by position in an index loop. The replay
shows i stepping through each index and result accumulating one pairwise
sum per iteration.
By hand
With NumPy
arr_a + arr_b adds the two arrays elementwise without an explicit loop.
NumPy iterates in C over the contiguous buffers, applying the addition to
every pair of aligned elements at once.
naive.py
a = [1, 2, 3, 4, 5, 6]
b = [10, 20, 30, 40, 50, 60]
result = []
for i in range(len(a)):
result.append(a[i] + b[i])
print('RESULT:', result)
library.py
import numpy as np
a = [1, 2, 3, 4, 5, 6]
b = [10, 20, 30, 40, 50, 60]
arr_a = np.array(a)
arr_b = np.array(b)
result = arr_a + arr_b
print('shape:', result.shape)
print('dtype:', result.dtype)
print('values:', result.tolist())
print('RESULT:', result.tolist())
shape: (6,)
dtype: int64
values: [11, 22, 33, 44, 55, 66]
RESULT: [11, 22, 33, 44, 55, 66]
Implementation notes
- Both arrays must have compatible shapes for
+to work. Two arrays of the same shape always match. Arrays of different shapes may still be compatible via broadcasting — covered in ch06. - The
+operator callsnp.add(arr_a, arr_b)under the hood. NumPy exposes all elementwise operations as both operators and named ufuncs; the ufunc form accepts an optionalout=argument to write results into a pre- allocated buffer. - Shape, dtype, and values are shown explicitly here because
ndarray.__repr__output varies with NumPy version and print options.