NumPy for Numerical Computing

Reviewed & published by Brayan K

NumPy is the foundation of scientific Python. Its ndarray stores numbers in a fast, contiguous, typed block and runs vectorized operations in compiled C — turning slow Python loops into fast array math used by pandas, scikit-learn, and PyTorch.

Learn NumPy for Numerical Computing in our free Python course — an interactive lesson with runnable examples, a practice exercise and a quick reference.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

What You'll Learn in This Lesson

🧱 1. The ndarray

🏗️ 2. Creating Arrays

NumPy has dedicated constructors for common patterns:

Function

Produces

np.arange(a, b, step)

Values from a up to b by step

np.zeros(shape) / np.ones(shape)

Array filled with 0s or 1s

np.linspace(a, b, n)

n evenly spaced points, a..b inclusive

📐 3. Shape, dtype, and reshape

Every array has a shape and a dtype . You can rearrange the layout with reshape :

The total number of elements must stay the same: a size-6 array can become 2x3 or 3x2, but not 2x4.

⚡ 4. Vectorized Operations

📡 5. Broadcasting

Broadcasting lets arrays of different but compatible shapes combine. A dimension of size 1 (or a scalar) is virtually stretched to match:

No data was copied to a bigger array — NumPy applies the rule virtually, which keeps it fast and memory-light.

🎯 6. Indexing, Slicing, and Masks

Index like lists, but also filter with boolean masks:

The expression a > 25 produces a boolean array; using it to index keeps only the True positions.

📊 7. Aggregations and axis

axis=0 collapses rows (one result per column); axis=1 collapses columns (one result per row).

🧪 Worked Example: A Whole Sensor Report

Each idea above is small on its own. This is what they look like working together: two temperature sensors, three readings each, and a report built without writing a single loop. Read the comments, run it, then change a number and predict what moves.

🎯 Your Turn: Reshape, Aggregate, Filter

Three blanks, one for each of the ideas you have just met. Fill them in, run it, and check your output against the expected block at the bottom of the snippet.

🚀 8. Why NumPy Is Faster Than Lists

Aspect

Python list

NumPy ndarray

Memory layout

Scattered pointers

Contiguous block

Element type

Mixed, boxed objects

Single fixed dtype

Loop execution

Python bytecode

Compiled C

For heavy numeric work, NumPy is often tens to hundreds of times faster than equivalent pure-Python loops.

🎯 Mini-Challenge: The Exam Board Report

Nothing is pre-written this time. You have a table of marks: three students down the rows, three exam papers across the columns. Produce the report described in the brief using array operations only — if you find yourself writing a for loop, there is a NumPy way to do it instead.

🎉 Conclusion

✔ Create arrays with arange, zeros, ones, linspace

Think in arrays, not loops — that is the NumPy mindset.

📋 Quick Reference — NumPy

Syntax

What it does

np.array([1, 2, 3])

Build an ndarray from a list

np.linspace(0, 1, 5)

Evenly spaced values

a.reshape(2, 3)

Reorganize into a new shape

a[a > 25]

Boolean mask filtering

a.sum(axis=0)

Aggregate along an axis

You now think in arrays and can run fast vectorized numeric code with NumPy.

Up next: Matplotlib — turn your data into clear charts and figures.

Practice quiz

What is the core data structure provided by NumPy?

  • The ndarray
  • The Series
  • The matrix list
  • The DataFrame

Answer: The ndarray. NumPy's central object is the ndarray (n-dimensional array), a fixed-type, contiguous block of numbers.

Which function creates evenly spaced values like 0, 2, 4, 6, 8?

  • np.linspace(0, 10)
  • np.ones(5)
  • np.arange(0, 10, 2)
  • np.zeros(5)

Answer: np.arange(0, 10, 2). np.arange(start, stop, step) works like range() but returns an ndarray, here 0,2,4,6,8.

What does np.linspace(0, 1, 5) return?

  • Five integers from 0 to 5
  • Five evenly spaced values from 0 to 1 inclusive
  • An error
  • Five random numbers

Answer: Five evenly spaced values from 0 to 1 inclusive. linspace(start, stop, num) returns num evenly spaced points including both endpoints: 0, 0.25, 0.5, 0.75, 1.

What does the .dtype attribute of an array tell you?

  • The number of dimensions
  • The total number of elements
  • The shape
  • The element data type (e.g. int64, float64)

Answer: The element data type (e.g. int64, float64). dtype reports the data type of the array's elements; all elements share one dtype.

If a has shape (2, 3), what does a.reshape(3, 2) produce?

  • A 3x2 array with the same 6 elements
  • A transposed copy with swapped values
  • A 2x3 array unchanged
  • An error, sizes differ

Answer: A 3x2 array with the same 6 elements. reshape returns a new view with the same data and total size (6 elements) arranged as 3 rows of 2.

What does arr * 2 do on a NumPy array arr?

  • Doubles only the first element
  • Doubles every element (vectorized)
  • Concatenates arr to itself
  • Raises a TypeError

Answer: Doubles every element (vectorized). Arithmetic is elementwise and vectorized: each element is multiplied by 2, with no Python loop.

What is broadcasting in NumPy?

  • Sorting arrays in place
  • Sending arrays over a network
  • Printing arrays to the console
  • Automatically stretching shapes so arrays of different sizes can combine elementwise

Answer: Automatically stretching shapes so arrays of different sizes can combine elementwise. Broadcasting lets NumPy combine arrays of compatible (not identical) shapes by virtually expanding dimensions of size 1.

Given a = np.array([1, 2, 3, 4]), what is a[a > 2]?

Boolean masking keeps elements where the condition is True, so a[a > 2] is array([3, 4]).

For a 2D array a, what does a.sum(axis=0) compute?

  • The sum across each row
  • The number of rows
  • The sum down each column
  • The sum of every element

Answer: The sum down each column. axis=0 collapses the rows, producing one sum per column; axis=1 would sum across each row.

Why is a NumPy vectorized operation usually faster than a Python for-loop?

  • It skips some elements
  • It runs as optimized C on contiguous typed data instead of per-element Python bytecode
  • It uses more memory
  • It always uses the GPU

Answer: It runs as optimized C on contiguous typed data instead of per-element Python bytecode. NumPy stores homogeneous data contiguously and runs loops in compiled C, avoiding per-element Python interpreter overhead.

Continue this course