Skip to content

Mojo Lists

A list holds many values of the same type, in order, and it can grow and shrink while your program runs. It’s the collection you’ll reach for most often, just like list in Python. Mojo’s version is called List, and it works a lot like Python’s, with a few differences that come from Mojo being a compiled, typed language. We’ll go through them one at a time.

You write a list with square brackets, and you tell Mojo it’s a List:

def main():
var scores: List[Int] = [90, 75, 62]
var names: List[String] = ["Ada", "Bo", "Cy"]
print(scores)
print(names)
print(len(scores))

Output:

[90, 75, 62]
[Ada, Bo, Cy]
3

List[Int] means “a list of Int values”. The part in square brackets is the element type, and every item in the list must have that type. A List[Int] can’t hold a string, and a List[String] can’t hold a number. len() tells you how many items are in the list.

To start with an empty list, write the type and ():

def main():
var todo = List[String]()
print(todo, len(todo))
var zeros = List[Int](length=4, fill=0)
print(zeros)

Output:

[] 0
[0, 0, 0, 0]

List[Int](length=4, fill=0) makes a list with 4 items that all start as 0. That’s handy when you know the size up front.

Each item has a position, called its index, starting at 0. Put the index in square brackets to read an item, or to change it:

def main():
var colors: List[String] = ["red", "green", "blue"]
print(colors[0])
print(colors[2])
colors[1] = "yellow"
print(colors)
print(colors[len(colors) - 1])

Output:

red
blue
[red, yellow, blue]
blue

The last line shows how to get the last item: colors[len(colors) - 1]. In Python you’d write colors[-1], but Mojo lists don’t support negative indexes. If you try, the compiler stops you and even suggests the fix:

def main():
var colors: List[String] = ["red", "green", "blue"]
print(colors[-1])
lists.mojo:1:5: error: function instantiation failed
def main():
^
lists.mojo:3:17: note: call expansion failed with parameter value(s): (..., ...)
print(colors[-1])
^
Mojo/stdlib/std/collections/list.mojo:1478:9: note: constraint failed: negative indexing is not supported, use e.g. `x[len(x) - 1]`
mojo: error: failed to run the pass manager

What about an index that’s too big? The compiler can’t always know how long a list will be, so this one is caught when the program runs. Mojo checks the index and stops the program with a clear message instead of reading random memory:

def main():
var colors: List[String] = ["red", "green", "blue"]
var i = 5
print(colors[i])
At: lists.mojo:4:17: Assert Error: index 5 is out of bounds, valid range is 0 to 2
mojo: error: execution crashed

We’ve left out the stack trace lines that follow. The fix is to check i < len(colors) before you read.

A list can change size. These are the methods you’ll use all the time:

def main():
var queue: List[String] = ["Ada", "Bo"]
queue.append("Cy")
queue.insert(0, "Dee")
queue.extend(["Eli", "Fay"])
print(queue)
var last = queue.pop()
print("popped", last)
var first = queue.pop(0)
print("popped", first)
print(queue)
queue.clear()
print(queue, len(queue))

Output:

[Dee, Ada, Bo, Cy, Eli, Fay]
popped Fay
popped Dee
[Ada, Bo, Cy, Eli]
[] 0
  • append(x) adds one item at the end.
  • insert(i, x) puts an item at position i and shifts the rest along.
  • extend(other) adds every item from another list.
  • pop() removes the last item and gives it back. pop(i) does the same for position i.
  • clear() removes everything.

These names match Python, so they should feel familiar. One Python method you won’t find is remove(value). Find the position first (next section) and then pop it.

To check whether a value is in a list, use in. To count how often it appears, use count():

def main():
var pets: List[String] = ["cat", "dog", "cat", "fish"]
print("dog" in pets)
print("bird" in pets)
print(pets.count("cat"))
print(pets.try_index("fish"))
print(pets.try_index("bird"))

Output:

True
False
2
3
None

try_index(x) gives you the position of the first match, or None if the value isn’t there. Its result is an Optional[Int], a value that may be missing. You’ll learn how to work with those in Mojo Optional. For now, think of it as “a number, or nothing”.

There’s also index(x), which works like Python’s: it returns the position, and it raises an error if the value isn’t found. Because it can raise, you need a try block or a function marked raises:

def main() raises:
var pets: List[String] = ["cat", "dog", "fish"]
var pos = pets.index("dog")
print("dog is at", pos)
_ = pets.pop(pos)
print(pets)

Output:

dog is at 1
[cat, fish]

That’s the “remove by value” pattern: find the index, then pop it. The _ = means “I don’t need the popped value”.

A for loop visits each item in order:

def main():
var prices: List[Int] = [3, 8, 5]
var total = 0
for p in prices:
total += p
print("total:", total)
for i, p in enumerate(prices):
print(i, p)

Output:

total: 16
0 3
1 8
2 5

enumerate() gives you the index and the item together, just like in Python.

Inside a plain for p in prices loop, p is read-only. If you want to change the items as you go, write for ref p in prices. Then p refers to the real item in the list:

def main():
var prices: List[Int] = [3, 8, 5]
for ref p in prices:
p *= 2
print(prices)

Output:

[6, 16, 10]

Without ref, the line p *= 2 is a compile error, because p can’t be changed.

Mojo has list comprehensions, the same short syntax Python has, for making a new list out of an old one:

def main():
var nums: List[Int] = [1, 2, 3, 4, 5, 6]
var squares = [n * n for n in nums]
var evens = [n for n in nums if n % 2 == 0]
print(squares)
print(evens)

Output:

[1, 4, 9, 16, 25, 36]
[2, 4, 6]

A comprehension always gives you a List, so you can keep appending to squares afterwards.

A slice picks out part of a list with start:end. Like Python, start is included and end isn’t:

def main():
var letters: List[String] = ["a", "b", "c", "d", "e"]
print(letters[1:3])
print(letters[2:])
print(letters[::2])

Output:

[b, c]
[c, d, e]
[a, c, e]

There’s one real difference from Python here. A simple slice like letters[1:3] doesn’t copy anything. It gives you a Span, a view that looks into the original list. That makes slicing cheap, and if you change an item through the view, the list changes too. A slice with a step, like [::2], gives you a new list. Views get their own lesson: Mojo Span.

Negative numbers don’t work in slices either. letters[-2:] stops the program with “slice start index -2 is out of bounds”. Use letters[len(letters) - 2:] instead.

In Python, b = a makes b another name for the same list. In Mojo, a list is a value: each variable owns its own list. Because copying a big list can be slow, Mojo won’t copy it behind your back:

def main():
var a: List[Int] = [1, 2, 3]
var b = a
print(b)
lists.mojo:3:13: error: value of type 'List[Int]' cannot be implicitly copied, it does not conform to 'ImplicitlyCopyable'
var b = a
^
lists.mojo:3:13: note: consider transferring the value with '^'
lists.mojo:3:13: note: you can copy it explicitly with '.copy()'
mojo: error: failed to parse the provided Mojo source module

The error gives you two choices. Call .copy() when you really want two separate lists, or use ^ to move the list into the new variable when you’re done with the old name:

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

Output:

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

After var c = a^, the name a can’t be used any more; the list now belongs to c. The Mojo manual’s page on value semantics explains why Mojo works this way, and the Ownership lessons cover it step by step.

A few more operations that work the way you’d guess:

def main():
var a: List[Int] = [1, 2]
var b: List[Int] = [3, 4]
var c = a + b.copy()
print(c)
print(a * 3)
c.reverse()
print(c)
a += [5, 6]
print(a)

Output:

[1, 2, 3, 4]
[1, 2, 1, 2, 1, 2]
[4, 3, 2, 1]
[1, 2, 5, 6]

+ makes a new list from two lists, * repeats a list, += adds items to the end, and reverse() flips a list in place. Notice the b.copy(): + takes ownership of the list on its right, so if you write plain a + b, Mojo gives you the same “cannot be implicitly copied” error as before. Pass a copy (or b^ if you don’t need b again). A literal like [5, 6] is fine, since nobody else owns it. The List API docs list every method, including a few we didn’t cover, like reserve() for making room ahead of time.

Python Mojo
Make a list xs = [1, 2, 3] var xs: List[Int] = [1, 2, 3]
Mixed types [1, "a"] is fine All items must have one type
Last item xs[-1] xs[len(xs) - 1]
Index too big IndexError you can catch The program stops with an error message
b = a Same list, two names Error: use a.copy() or a^
xs[1:3] A new list A view (Span) into xs
Remove by value xs.remove(x) xs.pop(xs.index(x))

Make a List[Int] with the scores 70, 85, 90 and 55. Append one more score, 100. Then print the number of scores and their average as a Float64.

Hint: add them up in a for loop, then divide Float64(total) by Float64(len(scores)).

Show solution
def main():
var scores: List[Int] = [70, 85, 90, 55]
scores.append(100)
var total = 0
for s in scores:
total += s
var average = Float64(total) / Float64(len(scores))
print("count:", len(scores))
print("average:", average)

Output:

count: 5
average: 80.0

If you divide two Int values, Mojo gives you an Int, so converting both to Float64 first keeps the decimal part.

Given ["a", "b", "a", "c", "b"], build a new list that keeps each letter only the first time it appears: [a, b, c].

Hint: start with an empty List[String]() and only append a letter if it’s not in the new list yet.

Show solution
def main():
var letters: List[String] = ["a", "b", "a", "c", "b"]
var unique = List[String]()
for x in letters:
if x not in unique:
unique.append(x)
print(unique)

Output:

[a, b, c]

not in checks the whole new list each time. That’s fine for small lists; for big ones, a Set (coming up in Mojo Sets) does the check much faster.

This program should print the last item and then a copy of the list with 40 added. It doesn’t compile. Fix it.

def main():
var nums: List[Int] = [10, 20, 30]
print(nums[-1])
var more = nums
more.append(40)
print(nums, more)

Hint: there are two problems, one on the print line and one on the var more line.

Show solution
def main():
var nums: List[Int] = [10, 20, 30]
print(nums[len(nums) - 1])
var more = nums.copy()
more.append(40)
print(nums, more)

Output:

30
[10, 20, 30] [10, 20, 30, 40]

Negative indexes aren’t allowed, so the last item is nums[len(nums) - 1]. And a list isn’t copied by =, so ask for a copy with .copy().

  • A list is written var xs: List[Int] = [1, 2, 3]. Without List, the brackets make a fixed-size Array.
  • Every item has the same type. Indexes start at 0, and len(xs) gives the size.
  • No negative indexes: the last item is xs[len(xs) - 1]. An index that’s too big stops the program.
  • Change size with append, insert, extend, pop and clear. Find things with in, count, try_index and index (which can raise).
  • Loop with for x in xs (read-only) or for ref x in xs (to change items).
  • xs[a:b] is a view, not a copy. b = a is an error: use a.copy() or move with a^.

Next up: dictionaries, for looking values up by a key instead of a position.

Quick check

1. What does var xs = [1, 2, 3] create in Mojo?
2. How do you read the last item of a list xs?
3. You have var a: List[Int] = [1, 2]. What happens with var b = a?
4. Which loop lets you change the items of a list in place?