Skip to content

Mojo For

A for loop goes through a group of things one by one: the numbers from 1 to 10, the names in a list, the characters in a word. For each one, it runs the loop body. It’s the loop you’ll use most, because it can’t forget to move on to the next item, the mistake that makes while loops run forever. If you know Python’s for, you already know most of this page.

range(n) gives you the numbers from 0 up to, but not including, n:

def main():
for i in range(4):
print("Round", i)

Output:

Round 0
Round 1
Round 2
Round 3

Each time round, i takes the next value: 0, 1, 2, 3. The 4 itself is not included, so range(4) gives exactly four numbers. i is the loop variable. You can call it anything; i is just the usual name for a counter.

range takes up to three numbers, the same way Python’s does:

def main():
for i in range(2, 6):
print(i, end=" ")
print("(from 2 up to 6)")
for i in range(0, 10, 3):
print(i, end=" ")
print("(steps of 3)")
for i in range(5, 0, -1):
print(i, end=" ")
print("Go!")

Output:

2 3 4 5 (from 2 up to 6)
0 3 6 9 (steps of 3)
5 4 3 2 1 Go!
Call Gives Meaning
range(4) 0, 1, 2, 3 from 0 up to 4
range(2, 6) 2, 3, 4, 5 from 2 up to 6
range(0, 10, 3) 0, 3, 6, 9 from 0 up to 10, in steps of 3
range(5, 0, -1) 5, 4, 3, 2, 1 counting down; the stop (0) is still left out

print(i, end=" ") puts a space after each number instead of a new line, and the print after each loop finishes the line. A range doesn’t build a list of all its numbers in memory; it hands them out one at a time, so range(1000000) doesn’t need more memory than range(3). The range docs list every form it accepts.

A very common job for a for loop: start a total at zero and add to it each round.

def main():
var total = 0
for n in range(1, 101):
total += n
print("1 + 2 + ... + 100 =", total)

Output:

1 + 2 + ... + 100 = 5050

range(1, 101) gives 1 to 100. Remember the stop is left out, so you write 101 to include 100.

When you don’t need the counter at all, name it _. That tells Mojo (and the reader) you only care about how many times the loop runs:

def main():
for _ in range(3):
print("Hip hip hooray!")

Output:

Hip hip hooray!
Hip hip hooray!
Hip hip hooray!

If you write for i in range(3): and never use i, the program still runs, but Mojo prints a warning: ref 'i' was never used, remove it?. Using _ keeps it quiet.

A for loop can go straight through the items of a list. No counter needed:

def main():
var fruits: List[String] = ["apple", "banana", "cherry"]
for fruit in fruits:
print("I like", fruit)

Output:

I like apple
I like banana
I like cherry

Remember from earlier lessons that you need the type List[String] here: a bare [...] in Mojo makes a fixed-size Array, not a list. Lists get their own lesson; for now, it’s enough to know you can loop over one.

Sometimes you want the position as well as the item. enumerate gives you both, as a pair, and you unpack them into two loop variables:

def main():
var fruits: List[String] = ["apple", "banana", "cherry"]
for i, fruit in enumerate(fruits):
print(i, fruit)
for n, fruit in enumerate(fruits, start=1):
print(t"{n}. {fruit}")

Output:

0 apple
1 banana
2 cherry
1. apple
2. banana
3. cherry

It counts from 0 by default. start=1 makes it count from 1, which is nicer for numbered lists that people read. enumerate is always available, with no import, just like in Python.

You might see for i in range(len(fruits)): and then fruits[i] in older code. It works, but enumerate is shorter and you can’t get the index wrong.

zip walks through two lists at the same time, giving you one item from each:

def main():
var names: List[String] = ["Ana", "Ben", "Cleo"]
var scores: List[Int] = [91, 78]
for name, score in zip(names, scores):
print(name, "scored", score)

Output:

Ana scored 91
Ben scored 78

zip stops at the end of the shorter list, so Cleo, who has no score, is left out without an error. The iter module docs list enumerate, zip and a few more helpers like map and chain.

reversed goes through a list, or a range, from the end to the start:

def main():
var steps: List[String] = ["open", "fill", "close"]
for step in reversed(steps):
print("Undo", step)

Output:

Undo close
Undo fill
Undo open

The list itself isn’t changed; you just visit it in the other order.

By default, the loop variable is read-only. It looks at each item but can’t change it:

def main():
var prices: List[Int] = [10, 20, 30]
for price in prices:
price += 1
print(prices)
hello.mojo:4:9: error: expression must be mutable for in-place operator destination
price += 1
^~~~~
mojo: error: failed to parse the provided Mojo source module

This is different from Python, where the code would run but quietly do nothing to the list. Mojo gives you two ways to say what you actually want:

def main():
var prices: List[Int] = [10, 20, 30]
for ref price in prices:
price += 1
print(prices)
for var price in prices:
price *= 100
print(price)
print(prices)

Output:

[11, 21, 31]
1100
2100
3100
[11, 21, 31]
  • for ref price in prices: makes price a reference to the real item in the list. Changing price changes the list.
  • for var price in prices: gives you a private copy of each item. You can change the copy, but the list stays the same.

ref and var come back in the ownership lessons. For loops, the rule of thumb is short: ref to change the list, var to play with a copy, nothing for just reading.

You can loop over a String too. Each round gives you one character, the way a person would count them:

def main():
var word = String("banana")
var count = 0
for letter in word:
if letter == "a":
count += 1
print("Number of a's:", count)

Output:

Number of a's: 3

“The way a person would count them” needs a bit of explaining, because text is stored as UTF-8, where one character can take several bytes. Mojo gives you three ways to go through a string:

Loop Each round gives you Use it for
for c in s: one grapheme: what you see on screen as one character counting or showing characters
for c in s.codepoints(): one Unicode codepoint (a Codepoint), which knows its number working with character codes
for b in s.bytes(): one byte of the UTF-8 encoding, as a number low-level work, file formats, hashing

For plain English text, all three line up. They differ when there are accents or emoji. Here’s a word where the accent is written as a separate “combining” mark (́), and a thumbs-up emoji with a skin tone:

def main():
var word = String("café")
var thumb = String("👍🏽")
var shown = 0
for _ in word:
shown += 1
print(shown, len(word.codepoints()), word.byte_length())
shown = 0
for _ in thumb:
shown += 1
print(shown, len(thumb.codepoints()), thumb.byte_length())

Output:

4 5 6
1 2 8

“café” shows as 4 characters, but it’s 5 codepoints (the accent is its own codepoint) and 6 bytes. The emoji is 1 character on screen, 2 codepoints and 8 bytes. A plain for c in s: gives you the number a person would expect.

And here are codepoints and bytes for a short ASCII string, where they match:

def main():
var s = String("Hi!")
for c in s.codepoints():
print(c, c.to_u32())
for b in s.bytes():
print(b)

Output:

H 72
i 105
! 33
72
105
33

c.to_u32() gives the codepoint’s number. The bytes are already numbers. The String docs explain all three views in detail, and the Strings in Depth lesson comes back to this.

The body of a for loop can contain another loop. The inner loop runs completely for each round of the outer one:

def main():
for row in range(1, 3):
for col in range(1, 4):
print(row, "x", col, "=", row * col)

Output:

1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6

The outer loop runs 2 times and the inner one 3 times per outer round, so the inner body runs 2 × 3 = 6 times.

In Python, the loop variable is still around after the loop, holding the last value. In Mojo it isn’t:

def main():
for i in range(3):
print(i)
print("Last:", i)
hello.mojo:4:20: error: use of unknown declaration 'i'
print("Last:", i)
^
mojo: error: failed to parse the provided Mojo source module

The loop variable belongs to the loop’s block, like a var inside an if. If you need a value after the loop, keep it in a variable you declared before the loop, like total in the examples above.

Print the sum of the even numbers from 2 to 20 (2 + 4 + … + 20). Use the step of range, not an if.

Hint: range(2, 21, 2).

Show solution
def main():
var total = 0
for n in range(2, 21, 2):
total += n
print("Sum of evens:", total)

Output:

Sum of evens: 110

The step of 2 skips the odd numbers, and the stop is 21 so that 20 is included.

Given var items: List[String] = ["eggs", "milk", "bread"], print:

1. eggs
2. milk
3. bread

Hint: enumerate with start=1, and a t-string like t"{n}. {item}".

Show solution
def main():
var items: List[String] = ["eggs", "milk", "bread"]
for n, item in enumerate(items, start=1):
print(t"{n}. {item}")

Output:

1. eggs
2. milk
3. bread

enumerate hands out pairs of (number, item), and the loop unpacks each pair into n and item.

Start with var prices: List[Int] = [5, 12, 8]. Double every price in the list with a for loop, then print the list. It should print [10, 24, 16].

Hint: a plain loop variable is read-only. Which keyword lets you change the item itself?

Show solution
def main():
var prices: List[Int] = [5, 12, 8]
for ref price in prices:
price *= 2
print(prices)

Output:

[10, 24, 16]

ref makes price refer to the item inside the list, so price *= 2 changes the list. With var you’d only double a copy, and the list would stay [5, 12, 8].

  • for x in something: runs the body once for each item. It can’t forget to move on.
  • range(stop), range(start, stop) and range(start, stop, step) give numbers; the stop is never included.
  • Use _ as the loop variable when you don’t need it.
  • enumerate gives (index, item) pairs, zip pairs up two lists (stopping at the shorter one), reversed goes backwards.
  • The loop variable is read-only. Use for ref x to change list items, for var x for a changeable copy.
  • for c in s goes through a string by grapheme (characters as you see them); use .codepoints() or .bytes() for the other views.
  • The loop variable doesn’t exist after the loop.

Next up: break and continue, how to leave a loop early or skip a round.

Quick check

1. Which numbers does range(1, 10, 3) give?
2. What does for i, name in enumerate(names, start=1): give you each round?
3. You want to add 1 to every number in a List[Int] with a for loop. Which loop works?
4. How many rounds does for c in s: run for a string that shows as "café" but is written with a separate combining accent?