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.
Looping over a range of numbers
Section titled “Looping over a range of numbers”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 0Round 1Round 2Round 3Each 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.
Start, stop and step
Section titled “Start, stop and step”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.
Adding things up
Section titled “Adding things up”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 = 5050range(1, 101) gives 1 to 100. Remember the stop is left out, so you write 101 to include 100.
Doing something n times
Section titled “Doing something n times”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.
Looping over a list
Section titled “Looping over a list”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 appleI like bananaI like cherryRemember 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.
Getting the index too: enumerate
Section titled “Getting the index too: enumerate”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 apple1 banana2 cherry1. apple2. banana3. cherryIt 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.
Two lists side by side: zip
Section titled “Two lists side by side: zip”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 91Ben scored 78zip 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.
Going backwards: reversed
Section titled “Going backwards: reversed”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 closeUndo fillUndo openThe list itself isn’t changed; you just visit it in the other order.
Changing the items in a list
Section titled “Changing the items in a list”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 moduleThis 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]110021003100[11, 21, 31]for ref price in prices:makespricea reference to the real item in the list. Changingpricechanges 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.
Looping over a string
Section titled “Looping over a string”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 61 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 72i 105! 337210533c.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.
Loops inside loops
Section titled “Loops inside loops”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 = 11 x 2 = 21 x 3 = 32 x 1 = 22 x 2 = 42 x 3 = 6The outer loop runs 2 times and the inner one 3 times per outer round, so the inner body runs 2 × 3 = 6 times.
The loop variable stays in the loop
Section titled “The loop variable stays in the loop”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 moduleThe 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.
Practice
Section titled “Practice”1. Add up the even numbers
Section titled “1. Add up the even numbers”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: 110The step of 2 skips the odd numbers, and the stop is 21 so that 20 is included.
2. A numbered shopping list
Section titled “2. A numbered shopping list”Given var items: List[String] = ["eggs", "milk", "bread"], print:
1. eggs2. milk3. breadHint: 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. eggs2. milk3. breadenumerate hands out pairs of (number, item), and the loop unpacks each pair into n and item.
3. Double every price
Section titled “3. Double every price”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)andrange(start, stop, step)give numbers; the stop is never included.- Use
_as the loop variable when you don’t need it. enumerategives (index, item) pairs,zippairs up two lists (stopping at the shorter one),reversedgoes backwards.- The loop variable is read-only. Use
for ref xto change list items,for var xfor a changeable copy. for c in sgoes 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
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Control flow: the
forstatement: the Mojo manual onforloops over lists, sets, dictionaries, ranges and Python objects. - For loops in the compound statements reference: unpacking in the loop target and the
varandrefloop variable bindings. range: every form ofrange, including negative steps.- The
itermodule:enumerate,zip,map,chainand the iteration traits behindfor. String: iterating by grapheme, codepoint or byte, andbyte_length.