Creating Arrays
Array from List
A Python list of integers copied element-by-element into a typed float buffer.
The replay shows v taking each integer value and buffer growing one float
at a time — making the typed-copy idea concrete before NumPy hides it.
By hand
With NumPy
np.array(values, dtype=float) performs the same typed copy in C, returning
a contiguous float64 buffer. The snapshot shows the array's shape, element
type, and values as a Python list.
naive.py
values = [1, 2, 3, 4, 5, 6]
buffer = []
for v in values:
buffer.append(float(v))
print('RESULT:', buffer)
library.py
import numpy as np
values = [1, 2, 3, 4, 5, 6]
arr = np.array(values, dtype=float)
print('shape:', arr.shape)
print('dtype:', arr.dtype)
print('values:', arr.tolist())
print('RESULT:', arr.tolist())
shape: (6,)
dtype: float64
values: [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
RESULT: [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
Implementation notes
dtype=floatis shorthand fornp.float64. NumPy stores every element in the same fixed-width type, so arithmetic on the array needs no per-element type dispatch — that is the source of most of NumPy's speed advantage over Python lists.- Omitting
dtypelets NumPy infer the type: an integer list infersint64, a mixed-type list often infersobject. Being explicit withdtype=floatavoids surprises in downstream arithmetic. arr.shapeis a tuple of dimension sizes. A 1-D array of 6 elements has shape(6,). Contrast with the 2-D case:np.array([[1,2],[3,4]]).shapegives(2, 2).- The element-by-element loop in the "By hand" half is the same pattern as
map-transforminpython-data-basics/ch02— both apply a function to each element and collect results. The difference is that NumPy stores the result in a typed C buffer rather than a Python list. - Shape, dtype, and values are shown explicitly here (rather than printing the
array directly) because
ndarray.__repr__output varies with NumPy version and print options such asnp.set_printoptions.