Create arrays

array, zeros, ones, full, arange, linspace, eye, and a seeded RNG.

You rarely type every cell by hand. Constructors fill a shape, walk a range, or draw a reproducible random sample.

Goal

Build arrays with array, zeros, ones, full, arange, linspace, eye, and a seeded RNG.

From nested lists

units = np.array([[12, 7, 2], [9, 6, 0], [3, 11, 1]], dtype=float)
print(units)

Zeros, ones, full

print(np.zeros((2, 3)))
print()
print(np.ones((2, 3), dtype=int))
print()
print(np.full((2, 3), 10.5))

zeros and ones default to float64. Pass dtype=int when you want integers.

Ranges

print(np.arange(0, 10, 2))
print(np.linspace(0, 1, 5))

arange is like range but returns an array — stop is excluded. linspace includes both ends and splits into num points.

Identity

print(np.eye(3))

Seeded random integers

A seed makes the draw repeatable — useful in a tutorial and in tests.

rng = np.random.default_rng(0)
# 3 cities × 3 products, like a noisy units grid
sample = rng.integers(0, 15, size=(3, 3))
print(sample)

Run it twice (paste the whole block again). You should get the same grid.

Tip

Prefer np.random.default_rng(seed) over the older np.random.seed. The Generator object is explicit.