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
- Install:
python -m pip install numpy. - Import:
import numpy as np. - Make an array:
np.array([...]). - 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.
Ravindra Bagale's Tip – मराठी
"प्रत्येक row वर loop" असा विचार आला की थांबा आणि विचारा: NumPy किंवा pandas हे संपूर्ण column वर करू शकतो का? बहुतेक वेळा हो.
Ravindra Bagale's Tip – हिंदी
"हर row पर loop" का ख़याल आए तो रुको और पूछो: क्या NumPy या pandas ये पूरे column पर कर सकता है? अक्सर हाँ.