Skip to content

Mojo for Python Cheat Sheet

You know how to do something in Python and want the Mojo way. This page is a lookup table for exactly that: Python on the left, Mojo 1.2 on the right. Every Mojo line in the tables also appears in the test programs further down, which we compiled and ran. For a slower walk through the same ideas, read Mojo for Python Developers.

Two things trip up nearly every Python developer, so keep them in mind while you read (Modular’s tips for Python developers cover more):

  • Code lives in functions. There’s no top-level code; the program starts at def main():.
  • New names need var. x = 5 only works if x already exists.
Python Mojo
x = 5 var x = 5
x: float = 1.5 var x: Float64 = 1.5
PI = 3.14 (constant by habit) comptime PI = 3.14 (a real constant)
if __name__ == "__main__": def main():
7 / 2 gives 3.5 7 / 2 with literals gives 3.5, but with two Int variables a / b gives 3
a / b on ints, as a float Float64(a) / Float64(b)
7 // 2, 7 % 2, 2 ** 10 the same
round(3.14159, 2) the same
print(a, b, sep=", ", end="") the same
f"{name} is {age}" t"{name} is {age}"
f"{x:.2f}" t"{round(x, 2)}" (no format specs)
x if cond else y the same
None None, inside an Optional[T]
Python Mojo
len(s) s.byte_length() or s.count_codepoints()
s[0] s[byte=0] (also codepoint= and grapheme=)
s[-1] s[byte=s.byte_length() - 1]
s.upper(), s.lower(), s.strip() the same
s.split(", "), s.split() the same
s.startswith("He"), s.find("x") the same
s.replace("a", "b") the same
"x" in s the same
"-" * 10 the same
", ".join(words) the same
"Age: " + str(36) "Age: " + String(36)
int("42"), float("2.5") Int("42"), Float64("2.5") (can raise)
"{} + {}".format(2, 3) the same (but no {:>8} specs)
Python Mojo
xs = [3, 1, 2] var xs: List[Int] = [3, 1, 2]
xs.append(4), xs.pop() the same
len(xs), x in xs the same
xs[-1] xs[len(xs) - 1]
xs.sort() sort(xs)
xs.sort(reverse=True) sort(xs, lambda (a: Int, b: Int) -> Bool: a > b)
ys = xs[:] or xs.copy() var ys = xs.copy()
ys = xs (same list, two names) no direct version: var ys = xs doesn’t compile; copy it or move it with xs^
xs[0:2] xs[0:2] (a view, not a new list)
[x * x for x in xs] the same
[x for x in range(10) if x % 2 == 0] the same
sum(xs), max(xs) no built-in: write a loop
xs.index(1) the same (can raise)
d = {"a": 1} var d: Dict[String, Int] = {"a": 1}
d["a"] the same (raises if missing)
d.get("z", 0) d.get("z").or_else(0)
d.pop("a", 0) the same
for k, v in d.items(): for item in d.items(): then item.key, item.value
s = set() var s = Set[Int]() after from std.collections import Set
t = ("x", 10), t[0] the same
for i, x in enumerate(xs): the same
zip(a, b), reversed(xs), range(0, 10, 2) the same
if not xs: (empty list) the same
Python Mojo
def area(w, h): def area(w: Int, h: Int) -> Int:
def power(base, exp=2): def power(base: Int, exp: Int = 2) -> Int:
power(2, exp=10) the same
def total(*nums): def total(*nums: Int) -> Int:
return lo, hi -> Tuple[Int, Int] and return (lo, hi)
lo, hi = min_max(xs) var lo, hi = min_max(xs)
lambda x: x * 2 lambda (x: Int) -> Int: x * 2
A function that may raise add raises: def parse(s: String) raises -> Int:
Changing a caller’s list mark the argument mut: def add(mut xs: List[Int]):
Python Mojo
class Point: struct Point:
self.x = x in __init__ creates a field declare var x: Int in the struct, then set it in def __init__(out self, x: Int):
@dataclass @fieldwise_init
def move(self): changing self def move(mut self):
@staticmethod the same
__add__, __eq__, __lt__ the same names
def __str__(self): conform to Writable and write def write_to(self, mut writer: Some[Writer]):
__len__ for len(obj) __len__ plus the Sized trait
class Square(Shape): (inheritance) trait Shape: and struct Square(Shape): (no inheritance)
p2 = p1 copies the reference var p2 = p1.copy() (needs Copyable)
Python Mojo
raise ValueError("bad") raise Error("bad")
except ValueError as e: except e: (one except per try)
finally: the same
with open("f.txt", "w") as f: the same
f.read(), f.write("hi\n") the same
Path("f.txt").read_text() the same, after from std.pathlib import Path
import math; math.sqrt(16) from std.math import sqrt then sqrt(16.0)
sys.argv argv() after from std.sys import argv
os.environ.get("X", "d") getenv("X", "d") after from std.os import getenv
input("Name: ") the same, inside a raises function
random.randint(1, 6) Int(random_si64(1, 6)) after from std.random import random_si64
import numpy as np var np = Python.import_module("numpy") after from std.python import Python
Python Mojo
python app.py mojo run app.mojo
uv add requests (add a package) uv add mojo (adds the Mojo compiler to a project)
pytest a program using std.testing and TestSuite, run with mojo run test_app.mojo
black app.py mojo format app.mojo
pdb mojo debug app.mojo
No compile step mojo build app.mojo -o app makes an executable

Here are the Mojo lines from the tables in two programs. Run them yourself to see each one work.

def main() raises:
var a = 7
var b = 2
print(7 / 2, a / b, Float64(a) / Float64(b), a // b, a % b, 2**10)
var x = 3.14159
var name = "Ann"
print(t"{name} has {round(x, 2)}", "{} + {}".format(2, 3))
var s = " Hello, World ".strip()
print(s.byte_length(), s.count_codepoints(), s[byte=0], s[byte=s.byte_length() - 1])
print(s.split(", "), "a b c".split(), s.lower(), s.find("World"), "World" in s)
print("Age: " + String(36), Int("42") + 1, Float64("2.5"))
var xs: List[Int] = [3, 1, 2]
sort(xs, lambda (a: Int, b: Int) -> Bool: a > b)
print(xs, xs[len(xs) - 1])
print(xs.index(1))
print(xs[0:2])
var sq = [x * x for x in xs]
var evens = [x for x in range(10) if x % 2 == 0]
print(sq, evens)
var ys = xs.copy()
ys.append(4)
print(len(xs), len(ys))
var d: Dict[String, Int] = {"a": 1}
print(d["a"], d.get("z").or_else(0))
var removed = d.pop("a", 0)
print(removed, len(d))
var maybe: Optional[Int] = None
print(maybe is None)
var empty: List[Int] = []
if not empty:
print("empty list")

Output:

3.5 3 3.5 3 1 1024
Ann has 3.14 2 + 3
12 12 H d
[Hello, World] [a, b, c] hello, world 7 True
Age: 36 43 2.5
[3, 2, 1] 1
2
[3, 2]
[9, 4, 1] [0, 2, 4, 6, 8]
3 4
1 0
1 0
True
empty list

And the functions, structs and modules:

from std.collections import Set
from std.math import sqrt
from std.os import getenv
from std.random import random_si64
from std.sys import argv
@fieldwise_init
struct Point(Copyable, Writable):
var x: Int
var y: Int
def move(mut self, dx: Int):
self.x += dx
def write_to(self, mut writer: Some[Writer]):
writer.write("Point(", self.x, ", ", self.y, ")")
def power(base: Int, exp: Int = 2) -> Int:
return base**exp
def total(*nums: Int) -> Int:
var sum = 0
for n in nums:
sum += n
return sum
def min_max(xs: List[Int]) -> Tuple[Int, Int]:
var lo = xs[0]
var hi = xs[0]
for x in xs:
lo = min(lo, x)
hi = max(hi, x)
return (lo, hi)
def main() raises:
print(power(3), power(2, exp=10), total(1, 2, 3))
var lo, hi = min_max([4, 1, 9])
print(lo, hi)
var double = lambda (x: Int) -> Int: x * 2
print(double(21))
var p1 = Point(1, 2)
var p2 = p1.copy()
p2.move(10)
print(p1, p2)
var seen = Set[Int]()
seen.add(3)
print(len(seen), sqrt(16.0), getenv("NOT_SET", "d"), len(argv()))
var roll = Int(random_si64(1, 6))
print(roll >= 1 and roll <= 6)
try:
raise Error("bad")
except e:
print("caught:", e)
finally:
print("finally")

Output:

9 1024 6
1 9
42
Point(1, 2) Point(11, 2)
1 4.0 d 1
True
caught: bad
finally
  • Wrap your code in def main(): and declare new names with var.
  • Give types to function arguments and collections: List[Int], Dict[String, Int].
  • Strings: byte_length() instead of len(), s[byte=0] instead of s[0], t-strings instead of f-strings.
  • Lists: sort(xs), xs.copy(), no negative indexes, no sum().
  • Classes become structs with traits; __str__ becomes Writable.
  • Errors use raises, raise Error(...) and a single except e:.

You’ve reached the end of the tutorial. Well done! The Mojo Next Steps page has ideas for where to go from here, and the Mojo Exercises are there whenever you want more practice.

Quick check

1. What is the Mojo version of Python's len(s) for a string s?
2. How do you write Python's f"{x:.2f}" in Mojo?
3. What replaces a Python class with a __str__ method?