Elementwise Math
Elementwise Product
Two 6-element lists multiplied position by position in an index loop. The
replay shows i stepping through each index and result accumulating one
pairwise product per iteration.
By hand
With NumPy
arr_a * arr_b multiplies the two arrays elementwise without an explicit loop,
producing the Hadamard (elementwise) product.
naive.py
a = [1, 2, 3, 4, 5, 6]
b = [2, 3, 4, 5, 6, 7]
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 = [2, 3, 4, 5, 6, 7]
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: [2, 6, 12, 20, 30, 42]
RESULT: [2, 6, 12, 20, 30, 42]
Implementation notes
- This is the Hadamard product: position
iof the output isa[i] * b[i]. It is NOT the dot product (sum of pairwise products). For dot product usenp.dot(a, b)ora @ b— that scalar output lesson is in the roadmap linear-algebra chapter. - Both arrays must have compatible shapes. The resulting array has the same shape as the inputs; no reduction occurs.
- Shape, dtype, and values are shown explicitly here because
ndarray.__repr__output varies with NumPy version and print options.