Skip to content

NumPy Tutorial for Beginners: Arrays, Axis and Broadcasting

Quick answer

A hands-on NumPy tutorial that explains arrays, indexing, vectorisation, the axis argument, broadcasting and views using one small marks example.

NumPy Tutorial for Beginners: Arrays, Axis and Broadcasting

This NumPy tutorial covers what a beginner needs to start using arrays with confidence: creating an ndarray, reading its shape and dtype, indexing and boolean filtering, vectorised maths, the axis argument, broadcasting and the difference between a view and a copy. NumPy is the array library that pandas, scikit-learn and most of Python's data stack rely on.

Key takeaways

  • A NumPy array holds values of one type in a fixed grid. That restriction is what makes it fast and memory-efficient for numeric work.
  • Replace loops with whole-array expressions. prices * 1.18 is the NumPy way, a for loop is not.
  • axis=0 collapses rows and gives one result per column. axis=1 collapses columns and gives one result per row.
  • Slices are views that share memory with the original array. Call .copy() when you need an independent array.

On this page:

How is a NumPy array different from a Python list?

A list is a flexible container for anything. An array is a grid of same-type numbers built for maths. The NumPy guide for absolute beginners says NumPy shines when there are large quantities of homogeneous, same-type data to process, and that this lets it improve speed and reduce memory consumption.

FeaturePython listNumPy array
Element typesMixed types allowedOne dtype for the whole array
x * 2Repeats the listDoubles every element
x + yJoins two listsAdds element by element
DimensionsNested lists, no shape checksTrue N-dimensional grid with a shape
Growing in placeappend is cheapSize is fixed, new array needed
Use it forGeneral programming, mixed recordsNumeric data, matrices, images, model inputs

Install with pip install numpy and import it under the name everyone uses:

import numpy as np

How do you create arrays?

Pass a list to np.array, or use a builder function when you need a pattern. Then check three attributes: shape, ndim and dtype.

The running example is an illustrative marks table: two students, three tests.

a = np.array([[72, 85, 90],
              [60, 75, 88]])

print(a.shape)   # (2, 3)  two rows, three columns
print(a.ndim)    # 2
print(a.dtype)   # int64
print(a.size)    # 6

The shape is a tuple giving the number of elements along each dimension. Get used to reading it before every operation, because most NumPy errors are shape errors.

Builder functions worth knowing

print(np.arange(0, 10, 2))       # [0 2 4 6 8]
print(np.linspace(0, 1, 5))      # [0.   0.25 0.5  0.75 1.  ]
print(np.zeros((2, 3)).shape)    # (2, 3)
print(np.arange(6).reshape(2, 3))
# [[0 1 2]
#  [3 4 5]]

rng = np.random.default_rng(42)
print(rng.integers(1, 7, size=5))   # five dice rolls, same every run because of the seed

How do you index, slice and filter?

Use [row, column] with commas, slices with colons, and a condition inside the brackets to filter. Counting starts at zero.

print(a[0, 1])     # 85        student 0, test 1
print(a[:, 0])     # [72 60]   every student's first test
print(a[1, 1:])    # [75 88]   student 1, tests 1 onwards
print(a[a > 80])   # [85 90 88] all marks above 80

The last line is boolean indexing. a > 80 produces an array of True and False of the same shape, and using it as an index keeps only the True positions. This is the same idea pandas uses when you filter rows, as shown in the pandas tutorial for beginners.

What is vectorisation and why does it matter?

Vectorisation means writing one expression that applies to the whole array, with the loop running inside NumPy's compiled code instead of in Python. The code is shorter and usually much faster.

prices = np.array([100, 250, 400])
print(prices * 1.18)          # [118. 295. 472.]  add 18% to every price

weights = np.array([0.2, 0.3, 0.5])
print(a @ weights)            # [84.9 78.5]  weighted score per student

The @ operator is matrix multiplication. For student 0: 72 x 0.2 + 85 x 0.3 + 90 x 0.5 = 14.4 + 25.5 + 45 = 84.9. That single line is the core calculation inside linear regression and neural network layers, which is why NumPy comes up in every list of maths for machine learning.

Measure the difference yourself

import timeit

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

print(timeit.timeit(lambda: [x * 2 for x in nums], number=5))
print(timeit.timeit(lambda: arr * 2, number=5))

The exact timings depend on your machine, so run it instead of trusting a quoted figure. The array version should finish in a small fraction of the list version's time.

How does the axis argument work?

The axis you name is the one that disappears. With a (2, 3) array, axis=0 removes the 2 and leaves three values, one per column. axis=1 removes the 3 and leaves two values, one per row.

print(a.mean())          # 78.33...  all six marks
print(a.mean(axis=0))    # [66. 80. 89.]  average per test
print(a.mean(axis=1))    # [82.33333333 74.33333333]  average per student

Check by hand: test 0 is (72 + 60) / 2 = 66. Student 0 is (72 + 85 + 90) / 3 = 82.33. If you ever forget the rule, compare the output's shape with the input's shape and see which dimension is gone. The same averages and spreads are explained from the statistics side in statistics for data science.

What is broadcasting?

Broadcasting is how NumPy does arithmetic on arrays of different shapes by stretching the smaller one, without copying data. The NumPy broadcasting documentation gives the rule: shapes are compared from the rightmost dimension, and two dimensions are compatible when they are equal or one of them is 1.

print(a - a.mean(axis=0))
# [[ 6.  5.  1.]
#  [-6. -5. -1.]]

Here a (2, 3) array minus a (3,) array works: the trailing dimensions are both 3, so the row of test averages is applied to each student. The result shows how far each student is from the test average.

Now a case that fails:

a + np.array([1, 2])
# ValueError: operands could not be broadcast together with shapes (2,3) (2,)

The trailing dimensions are 3 and 2: not equal, and neither is 1. To add one number per student, reshape it to a column with shape (2, 1): a + np.array([[1], [2]]).

Why did my original array change?

Because a slice is a view, not a copy. The NumPy documentation on copies and views states that basic indexing always creates views, while advanced indexing, such as indexing with a list or a boolean mask, always creates copies.

first = a[0]        # a view of row 0
first[0] = 0
print(a[0])         # [ 0 85 90]  the original changed too

safe = a[1].copy()  # independent copy
safe[0] = 0
print(a[1])         # [60 75 88]  unchanged

Views save memory on large arrays, which is the reason for the design. The rule for beginners: if you plan to modify a slice and still need the original, add .copy().

A short practice set

  1. Create a (3, 4) array with np.arange(12).reshape(3, 4) and print the sum of each row.
  2. Replace every value above 6 with 0 using a boolean mask.
  3. Subtract each row's mean from that row. Hint: you need keepdims=True or a reshape.

When these feel easy, move to tables with Python for data analysis or pick something from these Python projects for beginners.

Next step: type out every snippet above instead of copying it, and predict each output before you run it. If your goal is machine learning, the Artificial Intelligence and Machine Learning programme from Vishlesan i-Hub, IIT Patna is an 08-month programme.

Frequently asked questions

What is NumPy used for?

NumPy is used for fast numeric computing in Python: arrays, matrices, element-wise maths, linear algebra and random numbers. Libraries such as pandas and scikit-learn use NumPy arrays internally, so learning it helps across data analysis and machine learning.

Should I learn NumPy or pandas first?

For data analysis with spreadsheets and CSV files, start with pandas and learn NumPy alongside. For machine learning, image processing or maths-heavy work, start with NumPy. Either way you will end up using both.

What does axis=0 mean in NumPy?

axis=0 refers to the first dimension, the rows. An operation along axis=0 collapses the rows and returns one value per column. axis=1 collapses the columns and returns one value per row.

Why is NumPy faster than Python lists?

NumPy arrays store values of a single type in a compact block of memory, and operations run in compiled code over the whole array. Python lists store references to separate objects and loop in the interpreter, which adds overhead for numeric work.

What is the difference between a view and a copy in NumPy?

A view is a new array object that shares the same data as the original, so changing one changes the other. A copy duplicates the data and is independent. Basic slices return views. Use the copy method when you need separate data.

Share LinkedIn X WhatsApp
×

Our Courses

Practice-Based Learning Tracks, Supercharged By A.I.