Skip to main content
Albero Academy

Creating Arrays

The constructors you reach for constantly — zeros, ones, arange, linspace, eye and random.

Foundations10 min

Beyond wrapping a Python list with np.array, NumPy has a family of constructors for building the arrays you need most — filled arrays, ranges, evenly-spaced values, identity matrices and random data.

Filled arrays

zeros, ones, full
np.zeros((2, 3)) # 2×3 of 0.0
np.ones(5) # [1. 1. 1. 1. 1.]
np.full((2, 2), 7) # 2×2 filled with 7
np.empty((2, 2)) # uninitialised (fast; values are garbage)
np.zeros_like(a) # zeros with the same shape/dtype as a

Ranges & sequences

arange is like Python's range but returns an array; linspace gives evenly-spaced points including the endpoint:

arange & linspace
np.arange(0, 10, 2) # [0 2 4 6 8] (start, stop, step) — stop exclusive
np.linspace(0, 1, 5) # [0. 0.25 0.5 0.75 1.] — 5 points, endpoint included
np.eye(3) # 3×3 identity matrix

Random data

the modern Generator API
rng = np.random.default_rng(42) # seed → reproducible
rng.random((2, 3)) # 2×3 floats in [0, 1)
rng.integers(1, 7, size=10) # 10 dice rolls
rng.normal(0, 1, size=5) # 5 samples from a standard normal

Key takeaways

  1. 01np.array wraps a list; zeros/ones/full build filled arrays of a given shape.
  2. 02arange(start, stop, step) is range-as-array (stop exclusive); linspace(a, b, n) gives n evenly-spaced points including b.
  3. 03np.eye(n) makes an identity matrix.
  4. 04Use np.random.default_rng(seed) for reproducible random arrays.

Finished this chapter?

Mark it complete to track your progress through NumPy.