Elementwise Math
Scalar Multiply
Every element of a 6-element list scaled by constant k = 3 via a loop.
The replay shows v taking each value and result growing one scaled element
per iteration.
By hand
With NumPy
a * k multiplies every element of the array by the scalar k. NumPy treats
the scalar as if it were broadcast to match the array's shape — each element
is multiplied independently in the C loop.
naive.py
values = [1, 2, 3, 4, 5, 6]
k = 3
result = []
for v in values:
result.append(v * k)
print('RESULT:', result)
library.py
import numpy as np
values = [1, 2, 3, 4, 5, 6]
k = 3
a = np.array(values)
result = a * k
print('shape:', result.shape)
print('dtype:', result.dtype)
print('values:', result.tolist())
print('RESULT:', result.tolist())
shape: (6,)
dtype: int64
values: [3, 6, 9, 12, 15, 18]
RESULT: [3, 6, 9, 12, 15, 18]
Implementation notes
- A scalar operand is broadcast to match the array's shape:
a * kis equivalent toa * np.full(a.shape, k). This scalar-to-array broadcast is the simplest case of the general broadcasting rules in ch06. - The same pattern works for all arithmetic operators:
a + k,a - k,a / k,a ** k. For in-place scaling without allocation, usea *= k. - Shape, dtype, and values are shown explicitly here because
ndarray.__repr__output varies with NumPy version and print options.