CodeMIRAI
0 XP

Introduction to NumPy

2 min read 3 runnable examples Quiz included

NumPy (Numerical Python) is the foundation of data work in Python. pandas, scikit-learn, TensorFlow, PyTorch and matplotlib are all built on top of it. Its core is the ndarray: a fast, compact array of numbers.

Python
import numpy as np

prices = np.array([120, 250, 80, 300])
print(prices)
print(prices * 1.18)       # add 18% tax to every price at once
print(prices.sum(), prices.mean())

import numpy as np is the universal convention; you'll see np. everywhere.

Built on NumPy

LibraryWhat it does with NumPy arrays
pandastables whose columns are arrays
matplotlibcharts drawn from arrays
scikit-learnmachine-learning models that learn from arrays
OpenCVimages as arrays of pixels

Arrays vs lists

With a Python list, adding 18% tax means a loop or a comprehension. With a NumPy array, you write the maths once and it applies to every element. This is called vectorisation.

Python
import numpy as np

py_list = [1, 2, 3]
arr = np.array([1, 2, 3])

print(py_list * 2)     # repeats the list
print(arr * 2)         # multiplies each element
print(arr + arr)       # element-wise addition

Why it's fast

  • All elements share one type (for example 64-bit integers), stored side by side in memory.
  • The loops run in compiled C code, not in Python.

On large arrays NumPy is often 10 to 100 times faster than equivalent Python loops.

Python
import numpy as np
import time

numbers = list(range(1_000_000))
arr = np.arange(1_000_000)

t = time.time()
total = sum(n * n for n in numbers)
print(f"Python loop: {time.time() - t:.3f} s")

t = time.time()
total_np = (arr * arr).sum()
print(f"NumPy:       {time.time() - t:.3f} s")
print(total == total_np)
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.