Creating Arrays

Beyond wrapping an existing list, NumPy has several built-in functions for generating arrays of a given size or range directly — useful for placeholders, grids, and evenly spaced values.

Zeros and ones

np.zeros() and np.ones() take a shape and fill an array with that value. A single number makes a 1D array; a tuple like (2, 3) makes a 2D grid of that many rows and columns:

>>> placeholder arrays
zeros = np.zeros(4)
ones = np.ones((2, 3))
print(zeros)
print(ones)
Output
[0. 0. 0. 0.]
[[1. 1. 1.]
 [1. 1. 1.]]

Note the values print with a trailing .zeros() and ones() default to floating-point numbers, not integers.

arange and linspace

np.arange(start, stop, step) works like Python's built-in range() but returns an array. np.linspace(start, stop, num) instead takes a count and spaces that many values evenly between the start and stop, including both endpoints:

>>> ranges vs. even spacing
a = np.arange(0, 10, 2)
b = np.linspace(0, 1, 5)
print(a)
print(b)
Output
[0 2 4 6 8]
[0.   0.25 0.5  0.75 1.  ]

arange(0, 10, 2) steps by 2 and stops before reaching 10, the same "exclusive stop" rule as range(). linspace(0, 1, 5) instead asks for exactly 5 evenly spaced numbers between 0 and 1 — both endpoints included.

Note: for a fractional step, prefer linspace over arange when you need an exact number of points. np.arange(0, 1, 0.1) looks like it should produce 10 values, but floating-point rounding can make it unpredictably include or exclude the final value. np.linspace(0, 1, 10) doesn't have that problem, because you're specifying the count directly.