π’ NumPy for Beginners
in Python
Learn NumPy from scratch: arrays, dtypes, reshaping, slicing, boolean masks, broadcasting, vectorisation, random numbers and linear algebra, with runnable examples.
What this lesson is about
NumPy is the library that quietly sits underneath almost all numerical work in Python. Pandas stores its columns in NumPy arrays, scikit-learn expects NumPy arrays as input, Matplotlib plots them, and image and audio libraries hand you pixels and samples as arrays. If you want to do data analysis, machine learning or scientific computing in Python, you will meet NumPy in your first hour.
The big idea is the ndarray: a grid of values that all share one type and live next to each other in memory. Because the type is fixed and the layout is regular, NumPy can run your arithmetic in compiled code instead of the Python interpreter, so one line such as prices * 1.1 can replace a loop and often runs far faster. Learning to think in whole arrays rather than one element at a time is the real skill, and it is what this lesson is about.
I have organised the page in the order I would teach it in person. We start by creating arrays and understanding their shape and dtype, then slicing and boolean masks, then broadcasting and vectorisation, then axis-wise arithmetic, random numbers, linear algebra and finally the pitfalls that trip people up, especially views versus copies. Every example runs right in your browser, so press Run, change a number and see what happens.
What you will learn
- βCreate arrays with
array,arange,linspace,zerosandones - βRead and change
shape,ndimanddtype, and reshape safely - βSelect data with slices, fancy indexing and boolean masks
- βUse broadcasting to combine arrays of different shapes
- βReplace Python loops with vectorised expressions
- βReduce along an axis with
sum,mean,maxandargmax - βGenerate reproducible random data with
default_rng(seed) - βAvoid the classic view-versus-copy and integer-overflow traps
Why programmers should learn this
- β NumPy arrays are the common currency of the Python data stack, so Pandas, scikit-learn, SciPy and Matplotlib all assume you can read and write them.
- β Vectorised code is usually much shorter than the equivalent loop, which means fewer places for bugs to hide and code that reads like the maths it implements.
- β Large numeric jobs, such as processing a million sensor readings, become practical because the heavy work happens in compiled code rather than in the interpreter.
- β Machine learning is linear algebra on arrays, so understanding shapes and broadcasting makes tensors in PyTorch and similar tools feel familiar.
- β Many shape errors in data code come from not knowing what an array looks like; NumPy gives you the vocabulary (shape, axis, dtype) to debug them.
Your first arrays: creating and inspecting
A NumPy array looks like a list but behaves differently. Every element has the same dtype (data type), for example int64 or float64, and the array knows its shape, a tuple giving the length along each dimension. A list of lists becomes a two-dimensional array with shape (rows, columns).
You rarely type every value by hand. np.arange(start, stop, step) works like range but returns an array, np.linspace(a, b, n) gives n evenly spaced points including both ends, and np.zeros, np.ones and np.full make arrays of a constant. These are the building blocks for most real programs.
Notice in the output that ndim counts dimensions, size is the total number of elements and dtype is inferred from your data. If you mix integers and floats, NumPy promotes everything to float so the array stays uniform.
import numpy as np a = np.array([1, 2, 3, 4]) grid = np.array([[1, 2, 3], [4, 5, 6]]) print(a, a.dtype, a.shape) print(grid.shape, grid.ndim, grid.size) print(np.arange(0, 10, 3)) print(np.linspace(0, 1, 5)) print(np.zeros((2, 3))) print(np.full(3, 7)) mixed = np.array([1, 2.5, 3]) print(mixed.dtype)
[1 2 3 4] int64 (4,) (2, 3) 2 6 [0 3 6 9] [0. 0.25 0.5 0.75 1. ] [[0. 0. 0.] [0. 0. 0.]] [7 7 7] float64
Line by line
- 1Import NumPy under its conventional short name
np. - 3-4Build a one-dimensional array from a list and a two-dimensional one from a list of lists.
- 5-6Print the values, the dtype and the shape.
grid.shapeis(2, 3): two rows, three columns. - 8-9
arangecounts in steps (the stop value is excluded);linspaceincludes both endpoints and splits the range evenly. - 10-11Create arrays filled with zeros, or with a chosen constant.
- 13-14Mixing an int and floats forces the whole array to
float64.
Integer dtype is the default for whole numbers, so np.array([1, 2, 3]) / 2 still gives floats: division always produces floating-point results.
dtypes and reshaping
The dtype decides how much memory each value uses and what arithmetic is allowed. int8 holds -128 to 127 in one byte; float32 uses half the memory of float64 at lower precision. You choose a dtype when creating an array with the dtype= argument, or convert later with .astype(), which always returns a new array.
Reshaping changes how the same data is arranged without changing the data. A length-12 array can be viewed as (3, 4), (2, 6) or (2, 2, 3); the product of the dimensions must equal the size. Passing -1 for one dimension tells NumPy to work it out for you, which is handy when the number of rows is not known in advance.
Two related tools are .T (transpose, swapping rows and columns) and .ravel() (flatten to one dimension). Most of the time reshape returns a *view* of the original data rather than a copy, an idea I come back to in the pitfalls section.
import numpy as np x = np.arange(12) m = x.reshape(3, 4) print(m) print(x.reshape(2, -1).shape) print(m.T.shape) print(m.ravel()[:5]) f = np.array([1.9, 2.1, -3.7]) print(f.astype(int)) print(np.array([1, 2, 3], dtype=np.float32).dtype) print(np.array([1, 2, 3], dtype=np.int8).itemsize)
[[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] (2, 6) (4, 3) [0 1 2 3 4] [ 1 2 -3] float32 1
Line by line
- 3-5Create 0..11 and arrange it as 3 rows by 4 columns.
- 6
-1means 'figure this dimension out'; 12 elements in 2 rows gives 6 columns. - 7-8Transposing swaps the axes, so
(3, 4)becomes(4, 3).ravelflattens back to one dimension. - 10-11
astype(int)truncates toward zero, so -3.7 becomes -3 (not -4). - 12-13Pick a smaller dtype on purpose;
itemsizeshows the bytes per element.
Indexing, slicing and boolean masks
Slicing works like lists but across several dimensions at once: m[1, 2] picks one element, m[0:2, 1:] picks rows 0 and 1 and every column from 1 onwards, and m[:, 0] takes the first column. A slice always gives you a view into the original array, not an independent copy.
The feature that makes NumPy feel like magic is the boolean mask. A comparison such as data > 10 produces an array of True and False with the same shape, and indexing with that mask returns only the elements where it is True. You can combine conditions with & (and), | (or) and ~ (not), and each condition must be in its own parentheses because of operator precedence.
You can also index with a list of positions ('fancy indexing') to pick or reorder items, and assign through a mask to change many values at once, for example clipping all negative readings to zero. Unlike slices, fancy indexing and masks return copies when you read from them.
import numpy as np m = np.arange(1, 13).reshape(3, 4) print(m[1, 2], m[:, 0], m[0:2, 1:]) temps = np.array([18, 25, 31, 12, 29, 35, 22]) hot = temps > 28 print(hot) print(temps[hot]) print(temps[(temps > 15) & (temps < 30)]) print(temps[[0, 2, 4]]) temps[temps > 30] = 30 print(temps) print(np.where(temps >= 25, "warm", "cool"))
7 [1 5 9] [[2 3 4] [6 7 8]] [False False True False True True False] [31 29 35] [18 25 29 22] [18 31 29] [18 25 30 12 29 30 22] ['cool' 'warm' 'warm' 'cool' 'warm' 'warm' 'cool']
Line by line
- 3-4Build a 3x4 grid of 1..12, then pick a single value, a whole column, and a rectangular block.
- 6-9A comparison makes a boolean mask; indexing with it keeps only the hot days.
- 10Combine two conditions with
&. The parentheses are required. - 11Fancy indexing: pass a list of positions to select those elements.
- 13-14Assign through a mask to cap every value above 30 at 30.
- 15
np.where(cond, a, b)picks fromaorbelement by element.
Use & and |, not and and or, between arrays. Python's and asks for a single truth value and raises an error for arrays.
Vectorisation: replacing loops
Vectorisation means writing an operation on whole arrays and letting NumPy loop for you internally. a + b, a * 2, np.sqrt(a) and a > 3 all apply to every element. Functions with this behaviour are called *universal functions*, or ufuncs.
Why does it matter? A Python for loop pays interpreter overhead on every iteration: it looks up types, creates objects and runs bytecode. A ufunc does the same job in a tight compiled loop over contiguous memory. For large arrays the vectorised version is typically many times faster, and it is shorter too. I will not print timings here because they depend on your machine, but you can measure the difference yourself with timeit on an array of a million numbers.
Vectorising is a habit of thought: instead of asking 'what do I do with each item?', ask 'what is the whole-array expression?'. Below, a loop and a vectorised version compute the same BMI values, and we confirm that they agree.
import numpy as np
weights = np.array([60.0, 72.5, 85.0, 54.2])
heights = np.array([1.65, 1.80, 1.75, 1.60])
bmi_loop = []
for w, h in zip(weights, heights):
bmi_loop.append(w / h ** 2)
bmi_vec = weights / heights ** 2
print(np.round(bmi_vec, 1))
print(np.allclose(bmi_loop, bmi_vec))
print(np.sqrt(np.array([1, 4, 9, 16])))
print(np.maximum(np.array([1, 5, 3]), 2))[22. 22.4 27.8 21.2] True [1. 2. 3. 4.] [2 5 3]
Line by line
- 3-4Two parallel arrays: weights in kg and heights in metres.
- 6-8The loop version handles one pair at a time, in the Python interpreter.
- 10The vectorised version is one line: element-wise division and power across both arrays.
- 12-13Round for display, then use
np.allcloseto compare floating-point arrays safely. - 14-15Other ufuncs:
sqrttransforms each element;maximumcompares element-wise against a value or another array.
Not every loop can be vectorised, for example when each step depends on the previous result. In those cases look for built-ins such as np.cumsum, or consider a different algorithm before reaching for a loop.
Broadcasting
Broadcasting is the set of rules that lets NumPy combine arrays of different shapes. The simplest case is a scalar: m + 10 adds 10 to every element. The general rule is to line the shapes up from the right; two dimensions are compatible if they are equal or if one of them is 1, and a dimension of 1 is 'stretched' to match the other.
So a (3, 4) array plus a (4,) array works, because the row is stretched down all three rows. A (3, 1) column plus a (4,) row gives a (3, 4) result, the classic way to build a multiplication table without loops. When the shapes cannot be matched, such as (3, 4) with (3,), you get a ValueError that prints both shapes, which is your clue to reshape one of them.
np.newaxis (an alias for None) inserts a length-1 axis so you can turn a flat array into a column. A very common real use is centring data: subtract each column's mean from every row in one expression.
import numpy as np
m = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]])
row = np.array([10, 20, 30, 40])
print(m + row)
col = np.array([1, 2, 3])[:, np.newaxis]
print(col.shape)
print(col * np.array([1, 2, 3, 4]))
centred = m - m.mean(axis=0)
print(centred)
try:
m + np.array([1, 2, 3])
except ValueError as e:
print("shape mismatch")[[11 22 33 44] [15 26 37 48] [19 30 41 52]] (3, 1) [[ 1 2 3 4] [ 2 4 6 8] [ 3 6 9 12]] [[-4. -4. -4. -4.] [ 0. 0. 0. 0.] [ 4. 4. 4. 4.]] shape mismatch
Line by line
- 1-6A 3x4 grid and a length-4 row.
- 7The row is stretched across all three rows and added to each.
- 9-11Turn a flat array into a
(3, 1)column. Column times row produces a full(3, 4)table. - 13-14Subtract each column's mean:
m.mean(axis=0)has shape(4,)and broadcasts across rows. - 16-19Shapes
(3, 4)and(3,)do not line up from the right (4 versus 3), so NumPy raisesValueError.
Aggregations and the axis argument
Reductions such as sum, mean, min, max, std and argmax collapse an array. With no argument they reduce everything to one number. With axis=, they collapse just that dimension. This is where many beginners get confused, so remember: the axis you name is the one that disappears.
For a table with shape (rows, columns), axis=0 collapses the rows and leaves one value per column, while axis=1 collapses the columns and leaves one value per row. If you are unsure, check the output shape: reducing (3, 4) along axis 0 gives (4,).
argmax and argmin return the *position* of the largest or smallest value rather than the value itself, and cumsum returns running totals. Add keepdims=True when you want the reduced axis to remain as length 1 so the result broadcasts back against the original.
import numpy as np
sales = np.array([[120, 90, 100, 130],
[80, 110, 95, 105],
[150, 70, 60, 140]])
print(sales.sum())
print(sales.sum(axis=0))
print(sales.sum(axis=1))
print(sales.mean(axis=0).round(1))
print(sales.max(axis=1), sales.argmax(axis=1))
print(sales.cumsum(axis=1)[0])
share = sales / sales.sum(axis=1, keepdims=True)
print(share.round(2)[0])1250 [350 270 255 375] [440 390 420] [116.7 90. 85. 125. ] [130 110 150] [3 1 0] [120 210 310 440] [0.27 0.2 0.23 0.3 ]
Line by line
- 3-5Rows are three stores, columns are four weeks.
- 7No axis: one grand total.
- 8-9
axis=0collapses stores: one total per week.axis=1collapses weeks: one total per store. - 10-11Average per week, then the best week's value and its index for each store.
- 12Running total across weeks for the first store.
- 14-15
keepdims=Truekeeps shape(3, 1)so dividing gives each week's share of its store's total.
Random numbers and linear algebra
For random data, create a generator with rng = np.random.default_rng(seed) and call its methods: rng.random(n) for uniform values between 0 and 1, rng.integers(low, high, size) for whole numbers, rng.normal(mean, std, size) for a bell curve and rng.choice to sample from a list. Passing a seed makes the sequence reproducible, which matters for tests, tutorials and experiments you want to repeat. This newer API is preferred over the old np.random.seed global approach.
Linear algebra is built in. The @ operator multiplies matrices, * multiplies element by element (a very common mix-up), np.linalg.inv inverts a square matrix and np.linalg.solve(A, b) solves the system Ax = b. Prefer solve to computing the inverse yourself; it is both faster and more numerically stable.
The same toolkit gives you np.dot, np.linalg.norm for vector length and np.eye(n) for an identity matrix. These few functions cover most of what beginners need before moving to SciPy.
import numpy as np rng = np.random.default_rng(42) print(rng.integers(1, 7, size=5)) sample = rng.normal(50, 10, size=1000) print(round(float(sample.mean()), 1), round(float(sample.std()), 1)) print(rng.choice(["red", "green", "blue"], size=3)) A = np.array([[2.0, 1.0], [1.0, 3.0]]) b = np.array([5.0, 10.0]) x = np.linalg.solve(A, b) print(x) print(np.allclose(A @ x, b)) print(A * A) print(A @ A) print(round(float(np.linalg.norm([3, 4])), 1))
[1 5 4 3 3] 49.7 9.9 ['blue' 'green' 'green'] [1. 3.] True [[4. 1.] [1. 9.]] [[ 5. 5.] [ 5. 10.]] 5.0
Line by line
- 3Create a seeded generator; the same seed always gives the same numbers.
- 4-6Dice-like integers (high end excluded), then 1000 normal samples whose mean and spread land near 50 and 10.
- 7Randomly choose three colour names.
- 9-12Solve the 2x2 system
Ax = b, then verify by multiplying back with@. - 13-14Compare
*(element-wise) with@(matrix product): the results differ. - 15The norm of the vector (3, 4) is 5, from Pythagoras.
Seeded output can differ between NumPy major versions only if the generator algorithm changes; default_rng is designed to be stable for a given seed within the same bit generator.
Views, copies and other pitfalls
The most surprising NumPy behaviour is that slices and many reshapes are views: they share memory with the original. Modify the slice and the original changes too. This is deliberate, since it avoids copying large data, but it bites beginners. When you need independence, call .copy(). You can check with np.shares_memory(a, b).
Fancy indexing and boolean masks, by contrast, return copies. That is why a[a > 3] = 0 works as an assignment (it is a special in-place operation on a), but b = a[a > 3]; b[0] = 99 does not touch a.
The other classic trap is integer overflow. Fixed-size integers wrap silently: an int8 that holds 127 plus one becomes -128, with no error. Pick a dtype large enough for your values, or convert to a wider type before arithmetic. Finally, remember that comparing floats with == is unreliable; use np.isclose or np.allclose.
import numpy as np a = np.arange(6) view = a[1:4] view[0] = 99 print(a) safe = a[1:4].copy() safe[0] = -1 print(a) print(np.shares_memory(a, view), np.shares_memory(a, safe)) picked = a[a > 3] picked[0] = 0 print(a) small = np.array([127], dtype=np.int8) print(small + np.int8(1)) print(0.1 + 0.2 == 0.3, np.isclose(0.1 + 0.2, 0.3))
[ 0 99 2 3 4 5] [ 0 99 2 3 4 5] True False [ 0 99 2 3 4 5] [-128] False True
Line by line
- 3-5Slicing creates a view, so writing 99 through the view changes
aas well. - 7-9
.copy()breaks the link; changingsafeleavesaalone.shares_memoryconfirms it. - 11-13Masked reads give copies, so editing
pickeddoes not altera. - 15-16An 8-bit integer wraps from 127 to -128 on overflow.
- 17Floating-point sums are not exact; compare with
iscloseinstead of==.
Common mistakes
β Using and / or on arrays
Writing (a > 1) and (a < 5) raises 'truth value of an array is ambiguous'. Use & and | with each comparison in parentheses.
β Editing a slice and being surprised
Slices are views. If you assign into one, the parent array changes. Call .copy() whenever you want an independent array.
β Confusing axis=0 and axis=1
The axis you name is the one that gets collapsed. axis=0 on a table gives one value per column. When in doubt, print the result's shape.
β Using * when you mean matrix multiplication
* is element-wise. For the matrix product use @ or np.dot; check shapes with .shape first.
β Looping over an array in Python
A for loop over a large array throws away NumPy's speed advantage. Look for a ufunc, a mask or a reduction first, and loop only when each step truly depends on the last.
Quick quiz
Tap an answer. I explain every one, right or wrong.
Q1. What does np.arange(2, 10, 3) return?
Q2. m has shape (3, 4). What is the shape of m.sum(axis=0)?
axis=0 collapses the rows, leaving one total per column, so the shape is (4,).Q3. Which expression selects values of a that are greater than 2 AND less than 8?
& with parentheses. and fails on arrays and without parentheses & binds tighter than >.Q4. After v = a[1:3]; v[0] = 5, what happens to a?
Q5. A (3, 1) array is added to a (4,) array. What is the result's shape?
(3, 4).Q6. Why is rng = np.random.default_rng(7) useful?
Frequently asked questions
Is NumPy faster than a Python list?
+For numeric work on many elements, usually yes, because values are stored contiguously with one dtype and operations run in compiled code. For tiny arrays or heavy element-by-element Python logic the gap can vanish, so measure when it matters.
What is the difference between an array and a matrix?
+A NumPy array can have any number of dimensions. A matrix is simply a two-dimensional array. Modern code uses arrays and the @ operator instead of the old np.matrix class.
How do I install NumPy?
+Create a virtual environment and run pip install numpy. If you work in the browser examples on this site, it is loaded for you automatically.
When should I use Pandas instead?
+Use NumPy for homogeneous numeric grids and fast maths. Use Pandas when your data has labelled columns, mixed types, missing values or dates.
Why do I get a shape mismatch error?
+The two arrays cannot be broadcast together. Print both .shape values, align them from the right, and use reshape or np.newaxis to make each pair of dimensions equal or 1.
Key takeaways
- βAn ndarray holds same-typed values in a fixed shape; check
shape,ndimanddtypefirst when debugging. - βSlices are views, masks and fancy indexing give copies, and
.copy()makes independence explicit. - βBoolean masks combined with
&,|and~replace most filtering loops. - βBroadcasting aligns shapes from the right and stretches dimensions of length 1.
- βFor reductions, the axis you name is the one that disappears.
- βUse
default_rng(seed)for reproducible random data,@for matrix products andsolveinstead ofinv.