0Pricing
Python Academy · Lesson

Array Operations and Broadcasting

Perform vectorized arithmetic and understand broadcasting rules.

Array Operations and Broadcasting is a free Python Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Vectorised Arithmetic

NumPy applies arithmetic element-wise across entire arrays without Python loops — executed in optimised C code.

import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(a + b)    # [5 7 9]
print(a * b)    # [4 10 18]
print(a ** 2)   # [1 4 9]

Universal Functions (ufuncs)

NumPy's ufuncs apply element-wise C-level functions: np.sqrt, np.exp, np.log, np.sin, etc.

import numpy as np

x = np.linspace(0, np.pi, 5)
print(np.sin(x))   # [0. 0.707 1. 0.707 0.]
print(np.exp([1.0, 2.0, 3.0]))   # [2.718 7.389 20.086]

Reduction Operations

Reduce an array to a scalar (or lower-dim array) with np.sum, np.mean, np.max, np.min, np.std.

import numpy as np

m = np.array([[1, 2, 3], [4, 5, 6]])
print(np.sum(m))          # 21
print(np.sum(m, axis=0))  # [5 7 9]  — sum each column
print(np.sum(m, axis=1))  # [6 15]   — sum each row

Broadcasting Rules

Broadcasting stretches smaller arrays to match larger ones — without copying data. Rule: dimensions are aligned from the right; size-1 dims are stretched.

import numpy as np

a = np.array([[1], [2], [3]])  # shape (3,1)
b = np.array([10, 20, 30])     # shape (3,)

print(a + b)
# [[11 21 31]
#  [12 22 32]
#  [13 23 33]]

Broadcasting Scalar Operations

A scalar is broadcast across all elements of the array.

import numpy as np

arr = np.arange(6).reshape(2, 3)
print(arr + 10)
# [[10 11 12]
#  [13 14 15]]
print(arr * 0.5)
# [[0.  0.5 1. ]
#  [1.5 2.  2.5]]

Comparison and Boolean Operations

Comparisons produce boolean arrays. Combine with &, |, ~ (not Python and/or/not).

import numpy as np

arr = np.array([1, 5, 3, 8, 2])
print(arr > 3)           # [False  True False  True False]
print(arr[(arr > 2) & (arr < 7)])  # [5 3]

where()

np.where(condition, x, y) returns elements from x where True, from y where False.

import numpy as np

arr = np.array([-2, 3, -1, 4, 0])
result = np.where(arr >= 0, arr, 0)  # clip negatives to 0
print(result)   # [0 3 0 4 0]

Aggregations along Axes

Specify axis= to reduce along a particular dimension of a multi-dimensional array.

import numpy as np

data = np.arange(12).reshape(3, 4)
print(data.mean(axis=0))   # mean of each column → shape (4,)
print(data.mean(axis=1))   # mean of each row → shape (3,)

cumsum and diff

np.cumsum computes cumulative sums; np.diff computes differences between consecutive elements.

import numpy as np

prices = np.array([100, 110, 105, 115])
print(np.cumsum(prices))          # [100 210 315 430]
print(np.diff(prices))            # [10 -5 10] (daily changes)

Vectorised String Operations

np.char provides vectorised string operations on arrays of strings.

import numpy as np

words = np.array(["apple", "banana", "cherry"])
print(np.char.upper(words))       # ['APPLE' 'BANANA' 'CHERRY']
print(np.char.startswith(words, "a"))  # [True False False]

Performance vs Python Lists

NumPy is 10-100x faster than equivalent Python loops for numerical work because it executes in C without Python interpreter overhead.

import numpy as np, time

n = 1_000_000

start = time.perf_counter()
python_sum = sum(i**2 for i in range(n))
print(f"Python: {time.perf_counter()-start:.3f}s")

arr = np.arange(n)
start = time.perf_counter()
numpy_sum = (arr**2).sum()
print(f"NumPy:  {time.perf_counter()-start:.3f}s")

Quick Check

When adding a shape-(3,1) array to a shape-(3,) array, what shape is the result?

Recap

NumPy operations execute element-wise in C (no Python loops). Broadcasting stretches compatible shapes without copying. Use axis= for reductions along specific dimensions. Ufuncs (np.sin, np.exp, etc.) apply element-wise at C speed.

Frequently asked questions

Is the “Array Operations and Broadcasting” lesson free?

Yes — the full text of “Array Operations and Broadcasting” is free to read here on the web, and the Python Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO.

What will I learn in “Array Operations and Broadcasting”?

Perform vectorized arithmetic and understand broadcasting rules. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Python Academy?

No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Array Operations and Broadcasting” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Python Academy lesson?

Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. NumPy Arrays and dtypes
  2. Array Operations and Broadcasting
  3. Indexing, Slicing, and Fancy Indexing
  4. Linear Algebra with NumPy
← Back to Python Academy