Mojo Value Semantics
When you write b = a in Python, you don’t get a second list. You get a second name for the same list. Mojo works the other way round: every variable holds its own value, and changing one never changes another. This idea is called value semantics, and it’s the first step into Mojo’s ownership system. This page shows what it means in practice, one type at a time.
Python shares, Mojo doesn’t
Section titled “Python shares, Mojo doesn’t”Here’s something that surprises a lot of Python beginners:
a = [1, 2, 3]b = ab.append(4)print(a)print(b)Output:
[1, 2, 3, 4][1, 2, 3, 4]You changed b, but a changed too. That’s because Python lists use reference semantics: a and b are two labels stuck on one list. This is handy sometimes, and a source of bugs other times.
In Mojo, simple values like numbers behave like separate boxes:
def main(): var x = 1 var y = x y += 1 print("x:", x) print("y:", y)Output:
x: 1y: 2var y = x made a copy of the number. After that, x and y have nothing to do with each other. That’s value semantics: each variable owns its own value, and nobody else can change it behind its back.
Strings copy too
Section titled “Strings copy too”String works the same way as Int:
def main(): var a = String("cat") var b = a b += "s" print(a) print(b)Output:
catcatsb got its own copy of the text, so adding "s" to it leaves a alone. In Python you can’t see this difference with strings, because Python strings can’t be changed at all. In Mojo they can, and each variable changes only its own.
Lists need an explicit .copy()
Section titled “Lists need an explicit .copy()”Now try the Python example in Mojo:
def main(): var a: List[Int] = [1, 2, 3] var b = a b.append(4) print(a)hello.mojo:3:13: error: value of type 'List[Int]' cannot be implicitly copied, it does not conform to 'ImplicitlyCopyable' var b = a ^hello.mojo:3:13: note: consider transferring the value with '^'hello.mojo:3:13: note: you can copy it explicitly with '.copy()'mojo: error: failed to parse the provided Mojo source moduleMojo refuses. It doesn’t share the list like Python, and it also doesn’t quietly copy it. Copying a list means copying every item in it, which can be slow for a big list. So Mojo makes you say what you want. The error even lists your two choices:
.copy(): make a second, separate list.^: hand the list over tob, soacan’t be used any more. That’s called a move, and it gets its own lesson in Mojo Moving Values.
Here’s the copy:
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]Two lists, two owners. Changing b does nothing to a. Dict, Set and Array follow the same rule: plain var b = a is an error, and you pick .copy() or ^.
A copy is a full copy
Section titled “A copy is a full copy”In Python, list.copy() is a shallow copy: a list of lists still shares the inner lists. In Mojo, .copy() copies everything inside too:
def main(): var grid: List[List[Int]] = [[1, 2], [3, 4]] var copy = grid.copy() copy[0].append(99) print(grid) print(copy)Output:
[[1, 2], [3, 4]][[1, 2, 99], [3, 4]]copy[0] is its own inner list, so changing it doesn’t reach grid. The copy is complete and independent, which is exactly what value semantics promises.
Your own structs
Section titled “Your own structs”Structs (which you met in Mojo Structs) follow the same idea. A struct that conforms to Copyable gets a .copy() method, and copying it copies every field:
@fieldwise_initstruct Team(Copyable): var name: String var members: List[String]
def main(): var a = Team("red", ["Ana", "Ben"]) var b = a.copy() b.name = "blue" b.members.append("Cy") print(a.name, a.members) print(b.name, b.members)Output:
red [Ana, Ben]blue [Ana, Ben, Cy]Each team has its own name and its own list of members. If you leave out Copyable, the struct can’t be copied at all (only moved). And if you use ImplicitlyCopyable instead, a plain var b = a works, like it does for Int. That’s meant for small, cheap types. Mojo Common Traits explains these traits in detail.
Functions get a read-only view, not a copy
Section titled “Functions get a read-only view, not a copy”Value semantics also applies when you call a function. By default, the function gets a read-only reference to your value: it can look at the original, but it can’t change it. No copy is made, so passing a big list is cheap.
def add_two(y: Int): var z = y z += 2 print("z:", z)
def main(): var x = 1 add_two(x) print("x:", x)Output:
z: 3x: 1Inside add_two, the function made its own copy z to change. The caller’s x is safe. If the function tries to change its argument directly, Mojo stops it:
def add_item(items: List[String]): items.append("x")
def main(): var shopping: List[String] = ["milk"] add_item(shopping)hello.mojo:2:5: error: invalid call to 'append': invalid use of mutating method on rvalue of type 'List[String]' items.append("x") ^~~~~~~~~~~~mojo: error: failed to parse the provided Mojo source moduleThe wording is technical, but the meaning is simple: items is read-only here. In Python, add_item would happily change the caller’s list. In Mojo, a function only changes what you pass in when its signature says so, with mut. You’ll see how in Mojo Argument Conventions.
So can Mojo share anything?
Section titled “So can Mojo share anything?”Yes, but only when you ask for it, and in a way the compiler can check:
- A
mutargument lets a function change the caller’s value in place. - A
refgives you a second name for an existing value, without copying it (Mojo References & Origins). ArcPointerlets several variables share one value, like Python does (Mojo Pointers).
The official value semantics page puts it this way: Mojo doesn’t force every variable to have exclusive access, but it makes sure every value has one exclusive owner. That’s the topic of the next lesson.
Coming from Python?
Section titled “Coming from Python?”| Python | Mojo | |
|---|---|---|
b = a with numbers |
New name, numbers can’t change anyway | A copy |
b = a with a string |
Same string (strings can’t change) | A copy (strings can change) |
b = a with a list |
Same list, shared | Error: write a.copy() or a^ |
list.copy() |
Shallow copy | Full copy, inner lists too |
| Passing a list to a function | The function can change it | Read-only, unless the argument is mut |
Practice
Section titled “Practice”1. Two separate lists
Section titled “1. Two separate lists”This program should print [5, 6] and then [5, 6, 7]. Fix it.
def main(): var original: List[Int] = [5, 6] var changed = original changed.append(7) print(original) print(changed)Hint: you want two separate lists, and you still need original afterwards.
Show solution
def main(): var original: List[Int] = [5, 6] var changed = original.copy() changed.append(7) print(original) print(changed)Output:
[5, 6][5, 6, 7].copy() makes a second list. A move (original^) would also compile at that line, but then print(original) would fail, because original would be empty.
2. Copy a struct
Section titled “2. Copy a struct”Write a struct Settings with fields volume: Int and theme: String, conforming to Copyable. In main, make one called mine with volume 5 and theme "dark", copy it into yours, set yours.volume to 9, and print both volumes.
Hint: use @fieldwise_init to get the initializer for free, and .copy() to copy.
Show solution
@fieldwise_initstruct Settings(Copyable): var volume: Int var theme: String
def main(): var mine = Settings(5, "dark") var yours = mine.copy() yours.volume = 9 print(mine.volume, yours.volume)Output:
5 9yours is a separate value. Changing its volume can’t reach mine.
- Value semantics: each variable holds its own value; changing one never changes another.
Int,Float64,BoolandStringcopy on assignment:var b = ais a real copy.List,Dictand other bigger types don’t copy implicitly: write.copy()for a copy or^to move.- Mojo’s
.copy()is a full copy, unlike Python’s shallowlist.copy(). - A struct needs
Copyableto get.copy(), andImplicitlyCopyableto allow plainvar b = a. - Function arguments are read-only references by default: no copy, and no changes to the caller’s value.
Next up: ownership, the rules that decide who owns each value and when it’s cleaned up.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Value semantics: the Mojo manual’s explanation of copies, references and why the defaults are what they are.
- Intro to value ownership: how the stack and heap work, and why Mojo uses ownership instead of a garbage collector.
- Mojo ownership cheat sheet: a one-page table of what each kind of assignment does.
- Copyable trait: the standard library reference for
.copy()and the copy initializer.