Creating Arrays
There are three everyday ways to build a NumPy array. First, always import the library — the standard alias is np.
import numpy as np1From 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.
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.
length = 5 · stop is exclusive
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)
You choose how many points (5); NumPy computes the spacing for you.
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() | |
|---|---|---|---|
| Input | a list / tuple | start, stop, step | start, stop, count |
| You control | the values | the step size | the number of points |
| Stop value | — | excluded | included (by default) |
| Best for | known values | fixed-step sequences | fixed-count sequences |
What does np.arange(2, 11, 2) produce?
You want exactly 5 points between 0 and 1. Which do you use?