Ravindra BagaleCourses & study guides मराठी Track your progress

NumPy Tutorial for Beginners: Arrays, Maths and Filtering in Python

P12.1 What Is NumPy and Why Use It Instead of Lists

Why. With a list, adding 18% tax to 1 million prices needs a loop. With NumPy it is one line, and much faster.

What. NumPy gives an array: a list-like block where every value has the same type. Maths runs on all values at once (called vectorisation).

How.

Start with NumPy

  1. Install: python -m pip install numpy.
  2. Import: import numpy as np.
  3. Make an array: np.array([...]).
  4. Do maths on the whole array.

Worked example A — List vs array.

Step 1 — What we do. Prices of 4 products in a store in Toronto, plus $2 each.

Step 2 — Type and run this code.

import numpy as np
prices_list = [10, 20, 30, 40]
prices = np.array(prices_list)
print([p + 2 for p in prices_list])
print(prices + 2)

Step 3 — Output you should see.

[12, 22, 32, 42]
[12 22 32 42]

Step 4 — What it means. The list needs a loop (comprehension); the array just does + 2.

Worked example B — Speed check.

Step 1 — What we do. We add 1 to a million numbers both ways and compare the time.

Step 2 — Type and run this code.

import numpy as np, time
nums = list(range(1_000_000))
arr = np.arange(1_000_000)
t = time.time(); _ = [n + 1 for n in nums]; t_list = time.time() - t
t = time.time(); _ = arr + 1; t_np = time.time() - t
print("NumPy faster:", t_np < t_list)

Step 3 — Output you should see.

NumPy faster: True

Step 4 — What it means. NumPy is usually many times faster because the loop runs in optimised C code.

Python next to other languages — add 2 to every value. You do not need to learn these other languages. This only shows why Python is easier to read.

Language Code
Python list [p + 2 for p in prices]
NumPy prices + 2
JavaScript prices.map(p => p + 2)
Java Arrays.stream(prices).map(p -> p + 2).toArray()

Ravindra Bagale's Tip

Whenever you think "loop over every row", stop and ask: can NumPy or pandas do it on the whole column? Usually yes.