LearnWave
Learn it. Master it.

Introduction to NumPy

Operations on arrays

Tell element-wise multiplication from matrix multiplication.

Element-wise arithmetic. The operators +, -, *, /, % and the power operator act on each pair of corresponding elements. With A = [[3, 6], [4, 2]] and B = [[10, 20], [15, 12]]:

  • A + B is [[13, 26], [19, 14]]; A - B, A * B and A / B work pair by pair in the same way.
  • An array can also be combined with a single number: A * 2 doubles each element.
  • For element-wise operations the two arrays must have the same shape.

Matrix multiplication uses the @ operator: A @ B multiplies rows of A by columns of B and adds the products. For the arrays above, A @ B is [[120, 132], [70, 104]]. This is not the same as A * B.

Transpose: A.transpose() turns rows into columns, so a 3 × 4 array becomes 4 × 3. It returns a new view; the original array is unchanged.

Sorting: sort() arranges elements in ascending order, in place.

  • For a 1-D array: [1, 0, 2, -3, 6, 8, 4, 7] becomes [-3, 0, 1, 2, 4, 6, 7, 8].
  • For a 2-D array the default sorts each row (axis=1); sort(axis=0) sorts each column.

Example (new): with P = np.array([[1, 2], [3, 4]]) and Q = np.array([[5, 6], [7, 8]]), P * Q is [[5, 12], [21, 32]] (pair by pair), but P @ Q is [[1×5 + 2×7, 1×6 + 2×8], [3×5 + 4×7, 3×6 + 4×8]] = [[19, 22], [43, 50]].

* multiplies pairs; @ multiplies matrices.

Practise this lesson

Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.

No account, no email address. Opens the real product.