NumPy offers many ways to create arrays: from Python sequences, with factory functions like zeros and arange, or by reshaping existing buffers.
From Python sequences
import numpy as np
a = np.array([1, 2, 3])
b = np.array([[1, 2], [3, 4]])
print(a.shape, b.shape)
Factory functions
np.zeros(shape)— array of zerosnp.ones(shape)— array of onesnp.full(shape, fill_value)— constant fillnp.arange(start, stop, step)— like rangenp.linspace(start, stop, num)— evenly spaced floatsnp.eye(n)— identity matrix
dtype at creation
Pass dtype= to control element type: int32, float64, bool. Untyped literals infer from input values.
Important interview questions and answers
- Q: arange vs linspace?
A:arangeuses step size;linspacespecifies count of points including endpoints. - Q: Why np.array([1,2,3]) not just list?
A: Converts to ndarray with vectorized methods and contiguous storage.
Self-check
- Create a 3×3 identity matrix.
- What function gives 10 evenly spaced values from 0 to 1?
Tip: Prefer np.array with explicit dtype at boundaries.
Interview prep
- zeros vs empty?
zeros fills 0; empty allocates uninitialized memory—use empty for speed when overwriting.
- linspace vs arange?
linspace specifies count; arange specifies step.