Skip to content

Zig for Python Developers

Coming to Zig from Python is a bigger jump than coming from C or Go, and that’s fine. Python takes care of a lot for you: types are checked while the program runs, memory is freed for you, integers never overflow, and you never wait for a compiler. Zig asks you to do those things yourself, and in return you get small, fast programs that run without an interpreter and a compiler that catches whole groups of mistakes before you run anything. This page takes the Python ideas you know and shows the Zig version next to each one. The Python examples were run with Python 3.13 and the Zig ones with Zig 0.17.1.

In Python In Zig Lesson
python3 app.py zig run app.zig, or zig build-exe to get a program Zig Get Started
Any variable holds any type Every value has a fixed type, checked while compiling Zig Data Types
x = 5 (can change later) const x = 5; or var x: i32 = 5; Zig Variables
int (no size limit) i32, u8, u64… fixed sizes Zig Integers
str (Unicode text) []const u8 (bytes, usually UTF-8) Zig Strings
list Arrays, slices, std.ArrayList Zig ArrayList
dict std.StringHashMapUnmanaged, std.AutoHashMapUnmanaged Zig HashMap
None null, only in optional types ?T Zig Optionals
Exceptions, try/except Error unions, try, catch Zig Errors
with open(...) as f: defer file.close(io); Zig Defer
class struct with functions inside Zig Struct Methods
Garbage collection Allocators you pass in, freed by you Zig Memory
Indentation Braces { } and semicolons Zig Syntax

In Python, you run your source file and the interpreter reads it line by line. Zig compiles your file to machine code first, then runs it:

Terminal window
python3 hello.py # Python: the interpreter runs the file
zig run hello.zig # Zig: compile, then run, in one step
zig build-exe hello.zig # Zig: compile to a program called hello
./hello # run it; no Zig needed on this machine

That last line is a real difference. You can hand the hello file to someone who has never installed Zig or Python, and it runs. No virtual environment, no “which Python version do you have?”. And with -target, you can build it for Windows or a Raspberry Pi from your own laptop (Zig Cross-Compiling).

The cost is the wait for the compiler, and the fact that the compiler says no much more often than Python does. That second part is a feature, as you’ll see next.

Python checks types while the program runs, so a wrong type is found only when that line is reached:

def add(a, b):
return a + b
print(add(2, 3))
print(add("2", "3"))
print(add(2, "3"))

Output (the traceback is shortened):

5
23
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Two calls work (one of them probably not the way you wanted: "23"), and the third crashes. In Zig, every parameter has a type, and the compiler checks every call before anything runs:

const std = @import("std");
fn add(a: i32, b: i32) i32 {
return a + b;
}
pub fn main() void {
std.debug.print("{d}\n", .{add(2, "3")});
}
main.zig:8:39: error: expected type 'i32', found '*const [1:0]u8'
std.debug.print("{d}\n", .{add(2, "3")});
^~~
main.zig:3:19: note: parameter type declared here
fn add(a: i32, b: i32) i32 {
^~~

The message is a bit cryptic at first: *const [1:0]u8 is how Zig spells the type of the string literal "3". But it points at the exact spot, and you get it even if that line would only run once a year. If you use type hints with mypy, this is that idea, except it’s not optional and the program won’t build until it’s fixed.

You don’t have to write types everywhere, though. const total = add(2, 3); works out that total is an i32 on its own. Types are needed on function parameters, return values and struct fields.

A Python int grows as big as it needs to. 2 ** 64 is just 18446744073709551616. Zig integers have a fixed size that’s part of the type: a u8 holds 0 to 255, an i32 about plus or minus two billion. Going past the end is a bug Zig catches:

const std = @import("std");
pub fn main() void {
var level: u8 = 250;
for (0..10) |_| level += 1;
std.debug.print("level {d}\n", .{level});
}

You’ll see something like:

thread 5393 panic: integer overflow
main.zig:5:27: 0x11e3e00 in main (main.zig)
for (0..10) |_| level += 1;
^

That’s in a debug build, the default. The check costs a tiny bit of speed, so Zig lets you turn it off in fast builds, where an overflow silently gives a wrong number. If you want wrap-around on purpose (for hashes, for example), Zig has separate operators like +%. Zig Integer Overflow covers it, and Zig Integers explains how to pick a size. When in doubt, i64 or usize (for counts and indexes) are good defaults.

A Python str is a sequence of Unicode characters. A Zig string is a slice of bytes, []const u8, usually holding UTF-8 text. For plain English text you won’t notice the difference. With accents or emoji, you will:

const std = @import("std");
pub fn main() void {
const word = "héllo";
std.debug.print("{d} bytes\n", .{word.len});
std.debug.print("{d} code points\n", .{std.unicode.utf8CountCodepoints(word) catch 0});
}

Output:

6 bytes
5 code points

In Python, len("héllo") is 5. In Zig, .len is 6, because é takes two bytes in UTF-8. Things like .upper() exist for ASCII (std.ascii), but Zig’s standard library has no full Unicode case mapping. Zig Strings in Depth shows how to work with text properly.

Python frees objects for you when nothing uses them any more. Zig has no garbage collector. When you need memory whose size you only know while running (a list that grows, text you build), you ask an allocator for it and give it back when you’re done. Here’s a Python list and its Zig version:

scores = []
scores.append(70)
scores.append(85)
scores.append(92)
print(len(scores), "scores:", scores)
print("best:", max(scores))

Output:

3 scores: [70, 85, 92]
best: 92
const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var scores: std.ArrayList(u32) = .empty;
defer scores.deinit(gpa);
try scores.append(gpa, 70);
try scores.append(gpa, 85);
try scores.append(gpa, 92);
std.debug.print("{d} scores: {any}\n", .{ scores.items.len, scores.items });
std.debug.print("best: {d}\n", .{std.mem.max(u32, scores.items)});
}

Output:

3 scores: { 70, 85, 92 }
best: 92

The new parts:

  • init.gpa is an allocator Zig hands to main. Anything that might need memory takes it as a parameter: append(gpa, 70).
  • defer scores.deinit(gpa) frees the list when main ends. defer means “do this when we leave this block”, so you write the cleanup right next to the setup, a bit like Python’s with.
  • try is there because getting memory can fail, and Zig makes you deal with that (here, by passing the error on).
  • In a debug build, init.gpa reports leaks: forget the defer and you get a message pointing at the line that allocated.

It’s more to type than Python. The good news is that most code doesn’t allocate at all: fixed-size arrays, structs and string literals need no allocator. Zig Memory explains where things live and why Zig makes you choose.

Dictionaries work the same way. stock = {} becomes a std.StringHashMapUnmanaged(u32) that you put into with the allocator, and stock.get("kiwis") returns null instead of raising KeyError. Zig HashMap has the details.

Python raises an exception and you catch it somewhere up the stack, if anyone does. Zig has no exceptions. A function that can fail says so in its return type, and the caller has to handle it:

try:
with open("missing.txt") as f:
print(f.read())
except FileNotFoundError as err:
print("could not open:", err.strerror)

Output:

could not open: No such file or directory
const std = @import("std");
pub fn main(init: std.process.Init) void {
const io = init.io;
const text = std.Io.Dir.cwd().readFileAlloc(io, "missing.txt", init.gpa, .limited(4096)) catch |err| {
std.debug.print("could not open: {t}\n", .{err});
return;
};
defer init.gpa.free(text);
std.debug.print("{s}", .{text});
}

Output:

could not open: FileNotFound

readFileAlloc returns an error union: the file’s contents or an error. catch |err| { ... } is except; try would pass the error up to the caller, like letting an exception bubble up. The big difference: in Python, you can forget the try/except and find out when the program crashes. In Zig, you can’t use text without handling the error first; the compiler stops you. The Errors section of the language reference has the full rules. (io is how Zig does all input and output; Zig I/O Interface explains it.)

Zig has no classes and no inheritance, but a struct can have functions, which covers most of what you use classes for:

class Account:
def __init__(self, owner):
self.owner = owner
self.balance = 0
def deposit(self, amount):
self.balance += amount
acc = Account("Ada")
acc.deposit(50)
print(f"{acc.owner} has {acc.balance}")
const std = @import("std");
const Account = struct {
owner: []const u8,
balance: u64 = 0,
fn deposit(self: *Account, amount: u64) void {
self.balance += amount;
}
};
pub fn main() void {
var acc: Account = .{ .owner = "Ada" };
acc.deposit(50);
std.debug.print("{s} has {d}\n", .{ acc.owner, acc.balance });
}

Output:

Ada has 50

Both print Ada has 50. The fields are declared up front with their types, balance: u64 = 0 gives a default, and there’s no __init__: you create the struct with .{ .owner = "Ada" }. self is written out like in Python; it’s *Account (a pointer) because deposit changes the account. Zig Structs starts from the beginning.

You don’t have to choose one or the other. A common use of Zig is writing the slow part of a Python program. Zig can build a shared library with a C interface, and Python’s built-in ctypes module can load it:

fastmath.zig
export fn sum_of_squares(n: u32) u64 {
var total: u64 = 0;
var i: u64 = 1;
while (i <= n) : (i += 1) total += i * i;
return total;
}
Terminal window
zig build-lib -dynamic -O safe fastmath.zig # makes libfastmath.so on Linux
import ctypes
lib = ctypes.CDLL("./libfastmath.so")
lib.sum_of_squares.argtypes = [ctypes.c_uint32]
lib.sum_of_squares.restype = ctypes.c_uint64
print(lib.sum_of_squares(10))
print(sum(i * i for i in range(1, 11)))

Output:

385
385

export makes the function callable from C (and so from Python), and the argtypes/restype lines tell ctypes what types to use. On macOS the file is libfastmath.dylib, on Windows fastmath.dll. Whether it’s actually faster depends on how much work each call does; calling into a library has a cost of its own, so measure before you rewrite. Zig Export to C goes deeper.

  • Semicolons and braces. Indentation means nothing to Zig; zig fmt fixes the layout for you.
  • Unused variables are errors. Python doesn’t care; Zig refuses to compile. Write _ = x; while you’re still working.
  • const by default. A var that never changes is an error too, so use const unless you need to change it.
  • No None by accident. A plain i32 can never be null. Only ?i32 can, and you must check it before using the number.
  • Integer division and mixing types. 7 / 2 with integers is 3, and you can’t add an integer to a float without converting one of them (Zig Type Casting).
  • No REPL. There’s no interactive prompt. Small zig run files and zig test are the quickest way to try things.
  • Zig isn’t 1.0. Code from older blog posts often doesn’t compile on 0.17. This site sticks to 0.17.1.

Port this Python function. It returns the average of a list, or None for an empty list.

def average(nums):
if not nums:
return None
return sum(nums) / len(nums)

Hint: return ?f64. Convert the integer sum and length with @floatFromInt before dividing.

Show solution
const std = @import("std");
fn average(nums: []const i64) ?f64 {
if (nums.len == 0) return null;
var sum: i64 = 0;
for (nums) |n| sum += n;
const total: f64 = @floatFromInt(sum);
const count: f64 = @floatFromInt(nums.len);
return total / count;
}
pub fn main() void {
std.debug.print("{?d}\n", .{average(&.{ 2, 3, 7 })});
std.debug.print("{?d}\n", .{average(&.{})});
}

Output:

4
null

?f64 is Zig’s “a number or nothing”. {?d} prints an optional, showing null when it’s empty. The explicit conversions are how Zig makes you notice that you’re mixing integers and floats.

In Python you might write len(text.split()). Write a Zig function that counts the words in a string separated by spaces, using std.mem.tokenizeScalar.

Hint: var it = std.mem.tokenizeScalar(u8, text, ' '); then while (it.next()) |_| count += 1;.

Show solution
const std = @import("std");
fn countWords(text: []const u8) usize {
var it = std.mem.tokenizeScalar(u8, text, ' ');
var count: usize = 0;
while (it.next()) |_| count += 1;
return count;
}
pub fn main() void {
std.debug.print("{d}\n", .{countWords("zig is not python")});
}

Output:

4

tokenizeScalar skips repeated spaces, like Python’s split() with no argument. It doesn’t build a list, so no allocator is needed: it hands you one word at a time.

  • Zig compiles to a program that runs without Zig or Python installed.
  • Every value has a type, checked before the program runs.
  • Integers have a fixed size; overflow is caught in debug builds.
  • Strings are bytes ([]const u8), so .len counts bytes, not characters.
  • There’s no garbage collector: memory comes from an allocator, and defer frees it.
  • Errors are values in the return type, and the compiler makes you handle them.
  • Structs with functions replace classes, and Python can call Zig through ctypes.

Next up: Zig Get Started, installing Zig and running your first program.

Quick check

1. In Python, add(2, "3") fails when that line runs. When does Zig catch the same mistake?
2. What is "héllo".len in Zig?
3. What replaces Python's garbage collector in Zig?
4. How does Zig handle a function that can fail, like opening a file?