🔢Section 2 of 5

🔢 Part 1 — NumPy Basics

🎬 Why NumPy?

Python lists are flexible, but slow when you have millions of numbers. NumPy stores numbers in a contiguous block of memory and computes on them in compiled C — often 10–100× faster than equivalent pure-Python loops.

Step 1 — Create your first array

An array is just a grid of numbers. The simplest one is built from a Python list.

python
import numpy as np

a = np.array([1, 2, 3, 4, 5])
print(a)
print("type:", type(a).__name__)
print("dtype:", a.dtype)

Step 2 — Generators

You rarely type arrays by hand. Use these constructors:

python
import numpy as np

print("zeros:", np.zeros(4))
print("ones :", np.ones((2, 3)))
print("range:", np.arange(0, 10, 2))     # start, stop, step
print("lin  :", np.linspace(0, 1, 5))    # 5 evenly spaced points

Step 3 — Inspect the shape

Every array has a shape, ndim (number of dimensions),size and dtype.

Visual: a 2D array with shape = (3, 4)
0
1
2
3
4
5
6
7
8
9
10
11
← 4 columns →
python
import numpy as np

m = np.arange(12).reshape(3, 4)
print(m)
print("shape:", m.shape)
print("ndim :", m.ndim)
print("size :", m.size)
print("dtype:", m.dtype)

Step 4 — Indexing & slicing

Use [row, col] for 2D arrays. Slices use the usual start:stop syntax.

python
import numpy as np

m = np.arange(12).reshape(3, 4)
print("element [1, 2]:", m[1, 2])
print("first row    :", m[0])
print("last column  :", m[:, -1])
print("top-left 2x2 :\n", m[:2, :2])

Step 5 — Broadcasting & math

Operations apply element-wise. Smaller arrays are broadcast to match the larger shape.

python
import numpy as np

prices = np.array([10.0, 20.0, 15.0, 30.0])
qty    = np.array([3, 2, 5, 1])

revenue = prices * qty           # element-wise
print("revenue per item:", revenue)
print("total           :", revenue.sum())
print("average price   :", prices.mean())
print("max revenue     :", revenue.max())

# broadcasting: add 5% tax to every price
print("with tax        :", prices * 1.05)

Step 6 — Reshape & transpose

python
import numpy as np

a = np.arange(6)
print("flat   :", a)
print("3x2    :\n", a.reshape(3, 2))
print("2x3    :\n", a.reshape(2, 3))
print("transpose of 2x3:\n", a.reshape(2, 3).T)
🧠

Quick Check

Q1.What does np.arange(0, 10, 2) produce?
Q2.An array with shape (3, 4) has how many elements?
Q3.Which is the fastest way to multiply every element of an array by 2?