Mojo with NumPy
NumPy is the Python library for working with arrays of numbers, and a lot of Python code is built on it. Mojo uses NumPy the same way it uses any Python package: through Python interop. This page shows how to install it in your project, how to work with arrays from Mojo, and how to get the numbers into Mojo code (and back) so you can process them at Mojo speed.
Every example on this page was checked with Mojo 1.2, Python 3.13 and NumPy 2.5.
Installing NumPy
Section titled “Installing NumPy”NumPy isn’t part of Python itself, so your project needs it. Here’s a tiny program that uses it:
from std.python import Python
def main() raises: var np = Python.import_module("numpy") print(np.__version__)In a project made with uv init and uv add mojo (see Mojo Get Started), NumPy isn’t there yet, and the import fails when the program runs:
uv run mojo main.mojostack trace was not collected. Enable stack trace collection with environment variable `MODULAR_DEBUG=stack-trace-on-error`Unhandled exception caught during execution: No module named 'numpy'mojo: error: execution exited with a non-zero result: 1Add NumPy to the project and run it again:
uv add numpyuv run mojo main.mojoOutput:
2.5.5You’ll see whatever version uv installed for you. uv add puts NumPy into the project’s .venv and lists it in pyproject.toml. Remember that Mojo uses the python3 on your PATH, so run your program with uv run, or with the environment active (source .venv/bin/activate), or Mojo may find a different Python without NumPy.
Making and using arrays
Section titled “Making and using arrays”The convention in Python is import numpy as np. In Mojo, name the variable np and the rest of your code looks almost exactly like Python:
from std.python import Python
def main() raises: var np = Python.import_module("numpy") var temps = np.array([21.5, 23.0, 19.5, 25.0]) print(temps) print(temps.mean()) print(temps.max(), temps.argmax()) print(temps > 22) print(temps[temps > 22])Output:
[21.5 23. 19.5 25. ]22.2525.0 3[False True False True][23. 25.]np.array([...]) takes a Mojo list literal, and Mojo turns it into a Python list on the way in. Everything after that is NumPy: mean(), max(), argmax() (the position of the biggest value), and comparisons that give an array of True/False you can use to pick out values.
Two-dimensional arrays work too, and so does NumPy’s [row, column] indexing:
from std.python import Python
def main() raises: var np = Python.import_module("numpy") var grid = np.arange(6).reshape(2, 3) print(grid) print(grid.shape) print(grid[1, 2]) print(grid.sum(axis=0))Output:
[[0 1 2] [3 4 5]](2, 3)5[3 5 7]np.arange(6) makes 0 to 5, reshape(2, 3) arranges them in 2 rows and 3 columns, and sum(axis=0) adds up each column. All of it runs inside NumPy, at NumPy’s speed.
NumPy to Mojo and back, by copying
Section titled “NumPy to Mojo and back, by copying”NumPy arrays are Python objects. To use the numbers in plain Mojo code, the simplest way is to copy them into a Mojo List, one at a time, converting each with Float64(py=...). The other way round, you build a Python list and hand it to np.array:
from std.python import Python
def main() raises: var np = Python.import_module("numpy") var prices: List[Float64] = [1.5, 2.5, 4.0]
var py_list = Python.list() for p in prices: py_list.append(p) var arr = np.array(py_list) print(arr * 2)
var doubled = List[Float64]() for x in arr * 2: doubled.append(Float64(py=x)) print(doubled)Output:
[3. 5. 8.][3.0, 5.0, 8.0]The first print is NumPy’s way of showing an array; the second is a Mojo List[Float64]. A Mojo List doesn’t turn into a Python list by itself, which is why the loop with append is there. Mojo Python Types covers these conversions in detail.
This is fine for small arrays. For big ones it’s slow, because every single number goes through Python on its way across.
Sharing memory without copying
Section titled “Sharing memory without copying”A NumPy array keeps its numbers in one block of memory, one after another, just like a Mojo List. You can ask NumPy where that block is and read or write it directly from Mojo:
from std.python import Python
def main() raises: var np = Python.import_module("numpy") var arr = np.array([1.0, 2.0, 3.0, 4.0])
var ptr = arr.ctypes.data.unsafe_get_as_pointer[DType.float64]() var data = Span(unsafe_ptr=ptr, length=Int(py=arr.size))
var total: Float64 = 0 for x in data: total += x print("sum in Mojo:", total)
for ref x in data: x = x * 10 print("NumPy sees:", arr)Output:
sum in Mojo: 10.0NumPy sees: [10. 20. 30. 40.]Step by step:
arr.ctypes.datais NumPy’s way of telling you the memory address of the array’s numbers, as a Pythonint(seendarray.ctypesin the NumPy docs)..unsafe_get_as_pointer[DType.float64]()turns that address into a Mojo pointer toFloat64values.Span(unsafe_ptr=ptr, length=...)wraps the pointer and the length in a Span, so you can loop over it and index it like a list.for ref x in datachanges the numbers in place. NumPy sees the change, because there’s only one copy of the data.
You can also go the other way: let NumPy make an empty array, fill it from Mojo, then use NumPy on the result:
from std.python import Python
def main() raises: var np = Python.import_module("numpy") var n = 5 var squares = np.zeros(n, dtype=np.float64) var ptr = squares.ctypes.data.unsafe_get_as_pointer[DType.float64]() var data = Span(unsafe_ptr=ptr, length=n) for i in range(n): data[i] = Float64(i * i) print(squares) print(squares.sum())Output:
[ 0. 1. 4. 9. 16.]30.0How much faster is it?
Section titled “How much faster is it?”Here’s a measurement you can run yourself. It adds up a million numbers three ways: one item at a time through Python, through a pointer in Mojo, and with NumPy’s own sum():
from std.python import Pythonfrom std.time import perf_counter_ns
def main() raises: var np = Python.import_module("numpy") var arr = np.ones(1_000_000)
var start = perf_counter_ns() var slow: Float64 = 0 for x in arr: slow += Float64(py=x) print("one item at a time:", slow, "in", (perf_counter_ns() - start) // 1000, "µs")
start = perf_counter_ns() var ptr = arr.ctypes.data.unsafe_get_as_pointer[DType.float64]() var data = Span(unsafe_ptr=ptr, length=Int(py=arr.size)) var fast: Float64 = 0 for x in data: fast += x print("through a pointer: ", fast, "in", (perf_counter_ns() - start) // 1000, "µs")
start = perf_counter_ns() var np_sum = arr.sum() print("NumPy's own sum: ", np_sum, "in", (perf_counter_ns() - start) // 1000, "µs")What we got on a Linux machine with a 2.1 GHz Intel Xeon (your numbers will be different):
one item at a time: 1000000.0 in 44726 µsthrough a pointer: 1000000.0 in 1325 µsNumPy's own sum: 1000000.0 in 959 µsµs means microseconds, millionths of a second. Going one item at a time took about 45 milliseconds, because every number became a Python object and was converted back. Reading the memory directly took about 1 millisecond, roughly the same as NumPy’s own sum(), which is written in C. Over five runs the numbers moved around by a few hundred microseconds, but the pattern stayed the same.
The lesson isn’t “Mojo beats NumPy”. It’s this: use NumPy’s own functions for what NumPy already does, and when you need a loop NumPy doesn’t have, don’t go through Python one item at a time. Share the memory instead.
Practice
Section titled “Practice”1. Above average
Section titled “1. Above average”Make a NumPy array of the scores [72, 85, 90, 64, 88]. Print the average, then print only the scores above the average.
Hint: scores.mean() gives the average, and scores[scores > avg] picks values with a True/False mask.
Show solution
from std.python import Python
def main() raises: var np = Python.import_module("numpy") var scores = np.array([72, 85, 90, 64, 88]) var avg = scores.mean() print(avg) print(scores[scores > avg])Output:
79.8[85 90 88]avg stays a NumPy value, so scores > avg is a NumPy comparison that gives a mask, and indexing with the mask keeps the matching scores.
2. Clamp in place
Section titled “2. Clamp in place”Make the array np.array([-2.0, 5.0, 12.0, 7.0, -1.0]). Using a Span over its memory, change every negative number to 0.0 and every number above 10.0 to 10.0. Print the array from NumPy afterwards.
Hint: use for ref x in data: and change x with two if checks.
Show solution
from std.python import Python
def main() raises: var np = Python.import_module("numpy") var arr = np.array([-2.0, 5.0, 12.0, 7.0, -1.0]) var ptr = arr.ctypes.data.unsafe_get_as_pointer[DType.float64]() var data = Span(unsafe_ptr=ptr, length=Int(py=arr.size)) for ref x in data: if x < 0: x = 0.0 if x > 10: x = 10.0 print(arr)Output:
[ 0. 5. 10. 7. 0.]The values in the list literal have decimal points, so NumPy picks float64, which matches DType.float64. Since the span points into the array’s own memory, NumPy prints the changed values, and print(arr) at the end also keeps arr alive while the span is in use.
- Install NumPy into your project with
uv add numpy, and run withuv run(or the.venvactive) so Mojo finds it. var np = Python.import_module("numpy")and the rest reads like Python:np.array,mean(),reshape(),arr[1, 2].- Copy values across with a loop:
Float64(py=x)into a MojoList, andPython.list()+appendintonp.array. arr.ctypes.data.unsafe_get_as_pointer[DType.float64]()plus aSpanlets Mojo read and write NumPy’s memory without copying.- That’s unsafe: match the
dtype, use contiguous arrays, and keep the array alive. - Use NumPy’s own functions where they exist; share memory when you need your own loop.
Next up: Mojo Calling Mojo from Python, writing a Python module in Mojo.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- NumPy documentation: the official guide and reference for NumPy itself.
- NumPy: the absolute basics for beginners: arrays, shapes and indexing, if NumPy is new to you.
- Calling Python from Mojo: the Mojo manual’s page, which uses NumPy in its examples.
- PythonObject reference: includes
unsafe_get_as_pointer, used above to share memory.