Real code preallocates buffers, makes coordinate grids and test data far more often than it types literal lists.
Besides np.array(list), NumPy has constructors that create arrays of a given shape directly. They all take a shape (an int or a tuple) and an optional dtype:
np.zeros(shape),np.ones(shape): filled with 0 or 1,float64by defaultnp.full(shape, value): filled with any valuenp.empty(shape): allocated but not initialised; it contains whatever bytes were in memory. Use it only when you will overwrite every element.np.eye(n): identity matrix
For ranges there are two tools that look similar but answer different questions. np.arange(start, stop, step) works like Python's range (stop excluded) but returns an array and accepts float steps. np.linspace(start, stop, num) gives exactly num evenly spaced points and includes stop by default. Prefer linspace for floats: with arange(0, 1, 0.1) rounding error can make the number of elements surprising.
The *_like family copies shape and dtype from an existing array: np.zeros_like(a), np.ones_like(a), np.full_like(a, 7). This is handy for building an output buffer that matches an input.
np.asarray(x) converts to an array only if needed, returning x itself when it already is a suitable ndarray, whereas np.array(x) copies by default. In NumPy 2, np.array(x, copy=False) means "never copy" and raises if a copy is unavoidable, so use np.asarray for "copy only if necessary".
Example
import numpy as np
print(np.zeros((2, 3))) # 2x3 of 0.0
print(np.full(3, 7)) # [7 7 7]
print(np.eye(2, dtype=int)) # [[1 0] [0 1]]
print(np.arange(5)) # [0 1 2 3 4]
print(np.arange(2, 10, 3)) # [2 5 8]
print(np.linspace(0, 1, 5)) # [0. 0.25 0.5 0.75 1. ]
a = np.array([[1, 2], [3, 4]])
b = np.zeros_like(a) # int array of zeros, shape (2, 2)
print(b.dtype, b.shape) # int64 (2, 2)
c = np.asarray(a)
print(c is a) # True -- no copy madeRemember
zeros,ones,full,emptytake a shape and optional dtypearangeexcludes stop and steps by size;linspacegives a fixed count and includes stopnp.asarrayavoids needless copies;*_likemirrors an existing array
Watch out for
- Reading values from
np.emptybefore writing them: the contents are garbage, not zeros.