Creating Arrays
Zeros, Ones, and Full
Three fill loops build constant-value float buffers of length 4: all zeros, all ones, and all sevens. The replay shows the same append pattern repeated three times, with each list growing one element per iteration.
By hand
With NumPy
np.zeros(n), np.ones(n), and np.full(n, c) each allocate a typed buffer
and fill it in one call without an explicit loop. The snapshot shows each
array's shape, element type, and values in a labeled block.
naive.py
n = 4
c = 7.0
zeros = []
for i in range(n):
zeros.append(0.0)
ones = []
for i in range(n):
ones.append(1.0)
full = []
for i in range(n):
full.append(c)
print('RESULT:', (zeros, ones, full))
library.py
import numpy as np
n = 4
c = 7.0
zeros = np.zeros(n)
ones = np.ones(n)
full = np.full(n, c)
for name, arr in [('zeros', zeros), ('ones', ones), ('full', full)]:
print(f'{name}: shape: {arr.shape} dtype: {arr.dtype} values: {arr.tolist()}')
print('RESULT:', (zeros.tolist(), ones.tolist(), full.tolist()))
zeros: shape: (4,) dtype: float64 values: [0.0, 0.0, 0.0, 0.0]
ones: shape: (4,) dtype: float64 values: [1.0, 1.0, 1.0, 1.0]
full: shape: (4,) dtype: float64 values: [7.0, 7.0, 7.0, 7.0]
RESULT: ([0.0, 0.0, 0.0, 0.0], [1.0, 1.0, 1.0, 1.0], [7.0, 7.0, 7.0, 7.0])
Implementation notes
- All three functions default to
dtype=float64. Passdtype=int(or another dtype) to change the element type. np.zerosis the conventional way to pre-allocate an output buffer before filling it with computed values — a common pattern in the reduction and broadcasting lessons that follow.np.empty(n)is faster thannp.zeros(n)because it skips the initialisation step, but the contents are undefined. Use it only when every element will be overwritten before it is read.np.zeros_like(arr)andnp.ones_like(arr)create a zero/one array with the same shape and dtype as an existing array — useful when the shape is not known until runtime.- Shape, dtype, and values are shown explicitly here because
ndarray.__repr__output varies with NumPy version and print options.