Array Creation
NumPy ships a handful of array constructors. np.array wraps a Python sequence; zeros / ones / full create constant arrays; arange / linspace create ranges; random creates random arrays.
Every constructor you actually use
EXAMPLE
import numpy as np # From a Python sequence np.array([1, 2, 3]) # 1-D np.array([[1, 2], [3, 4]]) # 2-D # Constants np.zeros((3, 4)) # all 0.0 np.ones((2, 3), dtype=np.int32) np.full((2, 2), 7) np.empty((2, 2)) # uninitialised — faster, but random bytes # Ranges np.arange(0, 10, 2) # [0, 2, 4, 6, 8] np.linspace(0, 1, 5) # 5 evenly spaced from 0 to 1 np.logspace(0, 3, 4) # [1, 10, 100, 1000] # Identity np.eye(3) # 3x3 identity # Random — modern API via default_rng rng = np.random.default_rng(seed=42) rng.integers(0, 10, size=5) rng.normal(loc=0, scale=1, size=(2, 3)) rng.choice(['a', 'b', 'c'], size=4, p=[0.7, 0.2, 0.1]) # Like another array base = np.zeros((3, 3)) np.empty_like(base) np.ones_like(base, dtype=int)
Why it matters
np.empty is faster than np.zeros when you’ll overwrite the array immediately. Don’t use it if you need a known initial value — you’ll get whatever garbage was in memory.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
import numpy as np np.zeros((2, 3)) # zeros np.ones((2, 3)) # ones np.eye(3) # identity np.arange(0, 10, 2) # 0,2,4,6,8 np.linspace(0, 1, 5) # evenly spacedTry it Yourself »
Discussion
Loading…