LambdaLab
Informatics Practices · Class 12 · NumPy
NumPyHands-on⏱️ 8 min read

Creating Arrays

There are three everyday ways to build a NumPy array. First, always import the library — the standard alias is np.

example.py
import numpy as np

1From a list — np.array()

np.array() is the fundamental function to create arrays. It takes a list (or tuple, or other array-like object) as input.

playground.py

2Evenly spaced by step — np.arange()

Similar to Python's range(), but it returns a NumPy array and — unlike range() — it happily accepts non-integer start/stop/step values.

Syntax: np.arange(start, stop, step) stop is exclusive.

Try it — np.arange()
np.arange(0, 10, 2)
0
2
4
6
8

length = 5  ·  stop is exclusive

playground.py
range() vs np.arange()
Python's range(0.5, 5.5, 0.5) raises a TypeError — it only accepts integers. NumPy's np.arange(0.5, 5.5, 0.5) works perfectly and returns floats.

3Evenly spaced by count — np.linspace()

Creates evenly spaced numbers over an interval, but here you say how many values you want, rather than the step size.

Syntax: np.linspace(start, stop, num=50, endpoint=True)

Try it — np.linspace()
np.linspace(0, 10, 5, endpoint=True)
0
2.5
5
7.5
10

You choose how many points (5); NumPy computes the spacing for you.

playground.py
Which one should I use?
Reach for arange when you know the step between values. Reach for linspace when you know how many values you want — perfect for plotting a smooth range of points.

4Recap

np.array()np.arange()np.linspace()
Inputa list / tuplestart, stop, stepstart, stop, count
You controlthe valuesthe step sizethe number of points
Stop valueexcludedincluded (by default)
Best forknown valuesfixed-step sequencesfixed-count sequences
Quick Check

What does np.arange(2, 11, 2) produce?

Quick Check

You want exactly 5 points between 0 and 1. Which do you use?