IMPORTANT: To view this page as Markdown, append `.md` to the URL (e.g. /docs/manual/basics.md). For the complete Mojo documentation index, see llms.txt.
Skip to main content
Version: Nightly
For the complete Mojo documentation index, see llms.txt. Markdown versions of all pages are available by appending .md to any URL (e.g. /docs/manual/basics.md).

to_numpy_array

def to_numpy_array[dtype: DType, origin: Origin[mut=origin.mut]](data: Span[Scalar[dtype], origin]) -> PythonObject

Builds a 1-D NumPy array from a Mojo Span of scalars.

The data is copied into a new, independent NumPy array, so the result remains valid after data is later mutated or freed.

Example:

from std.python.numpy import to_numpy_array
from std.math import sin

var values = List[Float64](capacity=1024)
for i in range(1024):
var x = Float64(i) * 0.01
values.append(sin(x) * sin(x))

var arr = to_numpy_array(values) # an independent NumPy float64 array

Constraints:

dtype must be one of the fixed-width numeric dtypes supported by NumPy: int8-int64, uint8-uint64, float16, float32, or float64.

Parameters:

Args:

Returns:

PythonObject: A 1-D NumPy ndarray of dtype dtype and length len(data).

Raises:

If NumPy is unavailable, or if the underlying NumPy calls fail.