Skip to content

Mojo vs Python

Mojo looks so much like Python that it’s easy to think of it as “Python, but fast”. That’s partly true, and partly a trap. This page walks through what’s the same, what’s different, and what the speed difference looks like on a real (small) program, measured, not guessed.

You don’t need to know Mojo yet. If you know a bit of Python, every example here will make sense.

A lot of everyday code reads almost the same in both languages. Here’s a small Mojo program:

def average(numbers: List[Float64]) -> Float64:
var total = 0.0
for n in numbers:
total += n
return total / Float64(len(numbers))
def main():
var temps: List[Float64] = [21.5, 23.0, 19.8]
if len(temps) > 0:
print("Average:", average(temps))

Output:

Average: 21.433333333333334

If you’ve written Python, you can read all of it: def, indentation and colons, for ... in, if, return, len() and print(). The things Mojo shares with Python:

Python and Mojo
Blocks Indentation and a colon, no curly braces
Functions def name(...):
Loops for x in ...:, while, break, continue
Comments # like this and docstrings
Errors try, except, raise
Collections Lists, dictionaries and sets, plus comprehensions like [x * x for x in range(5)]
Printing print(a, b, sep=", ", end="")

The differences show up in the very same program. Look again at the lines with var and the types:

  • var total = 0.0: a new variable needs var in front of it. Plain total = 0.0 is an error if total doesn’t exist yet.
  • numbers: List[Float64] and -> Float64: arguments and return values have types. In Python they’re optional hints; in Mojo the compiler checks and uses them.
  • var temps: List[Float64] = [...]: a list holds one type of value. A Python list can mix "one", 2.0 and 3; a Mojo List can’t.
  • def main():: the program starts at main. Code at the top level of a file isn’t allowed.

There are bigger differences too, and the next sections cover the ones that matter most.

Python reads your file and runs it line by line. Mojo compiles the whole file to machine code first, and only then runs it. Even mojo run does this, which is why it takes a moment before anything prints.

That changes when you find mistakes. In Python, this program starts running and only fails when it reaches the bad line:

print("Starting...")
age = 36
print("Age: " + age)

Output:

Starting...
Traceback (most recent call last):
File "example.py", line 3, in <module>
print("Age: " + age)
~~~~~~~~^~~~~
TypeError: can only concatenate str (not "int") to str

The same mistake in Mojo never runs at all. The compiler stops it before the first line executes:

def main():
print("Starting...")
var age = 36
print("Age: " + age)
hello.mojo:4:21: error: no matching method in call to '__add__'
print("Age: " + age)
~~~~~~~~~~^~~
mojo: error: failed to parse the provided Mojo source module

Notice that Starting... isn’t printed. To fix it, turn the number into text with String(age). You’ll get used to this trade: the compiler is stricter, but whole groups of bugs never make it to the point where your program runs.

In Python, b = a makes b another name for the same list:

a = [1, 2, 3]
b = a
b.append(4)
print(a)

Output:

[1, 2, 3, 4]

In Mojo, each variable owns its value. Copying a list is something you ask for:

def main():
var a: List[Int] = [1, 2, 3]
var b = a.copy()
b.append(4)
print(a)
print(b)

Output:

[1, 2, 3]
[1, 2, 3, 4]

If you leave out .copy() and write var b = a, Mojo refuses: value of type 'List[Int]' cannot be implicitly copied. It doesn’t want to make an expensive copy behind your back. This idea is called value semantics, and it’s the start of Mojo’s ownership system. The official intro to value ownership explains why Mojo works this way; you’ll get there in Mojo Value Semantics.

A Python int grows as big as it needs to. A Mojo Int is a 64-bit machine integer (on a 64-bit computer), so it has a largest value. Go past it and the number wraps around:

def main():
var x: Int = 9223372036854775807
x += 1
print(x)

Output:

-9223372036854775808

Python prints 9223372036854775808 for the same code. Mojo doesn’t warn you here, so for really big numbers you have to pick your types with care. Mojo Integer Overflow goes into this.

This is the question everyone asks, and the honest answer is: it depends on what your code does. So here’s one measurement, with the details, rather than a big number from nowhere.

The program counts the prime numbers below 2,000,000 the slow way (trying every divisor). It’s pure loops and arithmetic, the kind of code where plain Python is at its slowest. Here’s the Mojo version; the Python version is the same code without var and the types:

def is_prime(n: Int) -> Bool:
if n < 2:
return False
var d = 2
while d * d <= n:
if n % d == 0:
return False
d += 1
return True
def main():
var count = 0
for n in range(2_000_000):
if is_prime(n):
count += 1
print(count)

Output:

148933

We ran both on the machine this tutorial is tested on: a cloud VM with a 4-core Intel Xeon at 2.1 GHz, Linux, Python 3.13 and Mojo 1.2. Each was run twice:

Version Time
Python 3.13 (python3 primes.py) about 11.1 to 11.4 seconds
Mojo, built first (mojo build, then ./primes) about 0.36 to 0.40 seconds
Mojo with mojo run (compiling included) about 1.3 to 1.5 seconds

So on this program, on this machine, the built Mojo program was roughly 30 times faster. Please read that with the fine print:

  • Your numbers will be different. Another computer, another Python version or another program gives another result.
  • It’s a best case for Mojo. If your Python code spends its time inside NumPy, pandas or PyTorch, the heavy work already runs in compiled C or C++, and rewriting the Python part in Mojo won’t give you a jump like this.
  • Compiling takes time. mojo run compiles every time, which matters for tiny scripts.
  • Mojo can go much further with SIMD and multiple CPU cores, but that’s extra work you write on purpose. Mojo Benchmarking shows how to measure properly.

No. Mojo isn’t a superset of Python, so most Python files won’t compile as Mojo. There are no Python-style classes or inheritance yet, variables have fixed types, and many built-ins work differently. The Mojo roadmap lists classes and other dynamic features as a later phase, and says plainly that Mojo may never become a full superset of Python.

What Mojo can do is use Python. You can import a Python module and call it, and the Python code runs in a normal Python interpreter:

from std.python import Python
def main() raises:
var statistics = Python.import_module("statistics")
var temps = Python.list(21.5, 23.0, 19.8)
print(statistics.mean(temps))

Output:

21.433333333333334

That’s Python’s own statistics module, called from Mojo. It’s handy for reusing libraries, but the Python parts run at Python speed. Mojo and Python covers this in depth.

You want to… Better fit
Write a quick script, glue tools together, explore data Python
Use a huge library ecosystem (web, data, ML tools) Python
Speed up a slow loop-heavy part of a program Mojo
Write code for GPUs without CUDA or C++ Mojo
Learn how memory, types and compilers work, with familiar syntax Mojo

Many people use both: Python for the big picture, Mojo for the parts that need to be fast.

This is valid Python. Rewrite it as a Mojo program that prints the same thing.

names = ["Ann", "Bo", "Cy"]
count = len(names)
print("We have " + str(count) + " names")

Hint: you need a main function, var for new variables, a typed List[String], and String(...) instead of str(...).

Show solution
def main():
var names: List[String] = ["Ann", "Bo", "Cy"]
var count = len(names)
print("We have " + String(count) + " names")

Output:

We have 3 names

The code moves into main, each new variable gets var, the list gets an element type, and String(count) turns the number into text.

Use Python’s math module from Mojo to print math.factorial(10).

Hint: Python.import_module("math") gives you the module. The function that holds it needs raises.

Show solution
from std.python import Python
def main() raises:
var math = Python.import_module("math")
print(math.factorial(10))

Output:

3628800

import_module can fail (for example if the module isn’t installed), so main is marked raises. The call itself runs in Python.

  • Mojo borrows Python’s syntax: def, indentation, for, if, try/except, print.
  • New variables need var, values have fixed types, and code lives inside functions.
  • Mojo is compiled: many mistakes are caught before your program runs at all.
  • b = a doesn’t share a list in Mojo; you copy with .copy() when you mean it.
  • Int has a fixed size and wraps on overflow; Python’s int doesn’t.
  • On a loop-heavy test program we measured about 30 times faster than Python; on code that already lives in NumPy, expect much less.
  • Mojo isn’t a Python superset, but it can import and call Python modules.

Next up: Mojo for Python Developers, side-by-side code for the things you do every day in Python.

Quick check

1. In Mojo, what happens if your program adds a number to a string with +, like "Age: " + age?
2. After var b = a.copy() and b.append(4), what is in a if it started as [1, 2, 3]?
3. Which statement about Mojo and Python code is true?
4. Why was the Mojo prime counter about 30 times faster than Python in our test?