Mojo Tuples
A tuple is a small, fixed group of values written in parentheses, like (3, 4) or ("Ada", 36). Unlike a list, the values in a tuple can have different types, but the number of values and their types are fixed when you write the tuple. You’ll use tuples to return more than one value from a function, to keep two or three things together for a moment, and as keys for grid positions.
Making a tuple
Section titled “Making a tuple”Put the values in parentheses, separated by commas:
def main(): var point = (3, 4) var person = ("Ada", 36, True) print(point) print(person) print(len(person))Output:
(3, 4)(Ada, 36, True)3point holds two Int values. person mixes a String, an Int and a Bool, which a list couldn’t do. len() gives the number of values.
If you want to write the type yourself, use Tuple[...] with the types in order:
def main(): var item: Tuple[String, Float64] = ("coffee", 3.5) var single = (7,) print(item) print(single)Output:
(coffee, 3.5)(7,)The type of item is Tuple[String, Float64]. A tuple with one value needs a trailing comma, like in Python: (7,). Without the comma, (7) is just the number 7 in parentheses.
Reading values by position
Section titled “Reading values by position”Each value has an index, starting at 0:
def main(): var person = ("Ada", 36, True) print(person[0]) print(person[1] + 1)Output:
Ada37person[1] is an Int, so you can do math with it. Mojo knows the type of every position at compile time.
That’s also why the index has to be a fixed number written in your code. You can’t use a variable as the index, and you can’t loop over a tuple with for:
def main(): var point = (3, 4) var i = 0 print(point[i])tuples.mojo:4:17: error: invalid call to '__getitem_param__': cannot use a dynamic value in a parameter list print(point[i]) ^mojo: error: failed to parse the provided Mojo source moduleThink about it this way: if i could be anything, Mojo couldn’t know whether person[i] is a String or an Int. If you need to loop over values or pick one with a variable, you want a List (when all values have the same type) or a struct (when they don’t).
Unpacking
Section titled “Unpacking”Unpacking pulls the values out of a tuple into separate variables in one line:
def main(): var person = ("Ada", 36, True) var name, age, admin = person print(name) print(age) print(admin)Output:
Ada36TrueThe number of names on the left must match the number of values in the tuple. You can also write the names in parentheses, var (name, age, admin) = person, if you find that clearer.
Unpacking gives you the classic swap, without a temporary variable:
def main(): var a = 1 var b = 2 a, b = b, a print(a, b)Output:
2 1The right side builds the tuple (2, 1) first, then unpacks it into a and b.
Returning several values from a function
Section titled “Returning several values from a function”This is where tuples help most. A function can only return one thing, but that thing can be a tuple:
def min_max(nums: List[Int]) -> Tuple[Int, Int]: var lo = nums[0] var hi = nums[0] for n in nums: if n < lo: lo = n if n > hi: hi = n return lo, hi
def main(): var lowest, highest = min_max([4, 9, 1, 7]) print("lowest:", lowest) print("highest:", highest)Output:
lowest: 1highest: 9The return type Tuple[Int, Int] says “two Int values”. return lo, hi makes the tuple (the parentheses are optional), and the caller unpacks it straight away. The Mojo manual’s Types page shows the same patterns.
Changing a value in a tuple
Section titled “Changing a value in a tuple”Here Mojo is different from Python. A Python tuple can’t be changed. In Mojo, the shape of a tuple is fixed (how many values and their types), but you can replace a value if the tuple is in a var:
def main(): var point = (3, 4) point[0] = 10 print(point)Output:
(10, 4)You still can’t add or remove values, and point[0] must stay an Int. If you come from Python, don’t count on a tuple being “frozen”. If you want a value nobody can change, make it a comptime constant or keep it in a variable you don’t reassign.
Comparing tuples
Section titled “Comparing tuples”Tuples compare position by position, from left to right, the same way Python does:
def main(): print((1, 2) == (1, 2)) print((1, 2) < (1, 3)) print((2, 0) > (1, 9)) var person = ("Ada", 36, True) print(36 in person)Output:
TrueTrueTrueTrue(2, 0) > (1, 9) is True because the first values already decide it: 2 is bigger than 1, so the second values don’t matter. in checks whether any value in the tuple equals the one you ask about.
Lists of tuples
Section titled “Lists of tuples”A list where each item is a tuple is a quick way to store small records. A for loop can unpack each tuple as it goes:
def main(): var scores: List[Tuple[String, Int]] = [("Ada", 91), ("Bo", 78), ("Cy", 85)] for name, score in scores: print(name, "scored", score)Output:
Ada scored 91Bo scored 78Cy scored 85The list’s type is List[Tuple[String, Int]]. Every item has to be a (String, Int) pair.
Coming from Python?
Section titled “Coming from Python?”| Python | Mojo | |
|---|---|---|
| Make one | t = (1, "a") |
var t = (1, "a") |
| Type annotation | tuple[int, str] |
Tuple[Int, String] |
| Change a value | Not allowed | Allowed: t[0] = 5 (in a var) |
| Index with a variable | t[i] works |
Compile error: the index must be a fixed number |
| Loop over it | for x in t: |
Not supported |
| Unpack | a, b = t |
var a, b = t |
| Return several values | return a, b |
Same, with -> Tuple[A, B] |
Practice
Section titled “Practice”1. Sum and count
Section titled “1. Sum and count”Write a function stats(nums: List[Int]) -> Tuple[Int, Int] that returns the sum and the number of items. Call it with [5, 10, 15] and print sum: 30 count: 3.
Hint: build both values in one loop, then return total, len(nums).
Show solution
def stats(nums: List[Int]) -> Tuple[Int, Int]: var total = 0 for n in nums: total += n return total, len(nums)
def main(): var total, count = stats([5, 10, 15]) print("sum:", total, "count:", count)Output:
sum: 30 count: 3The caller unpacks the tuple into two names right away, so it never has to use [0] and [1].
2. Best score
Section titled “2. Best score”Given [("Ada", 91), ("Bo", 78), ("Cy", 95)] as a List[Tuple[String, Int]], print the name with the highest score.
Hint: keep a best_name and a best_score variable, and update both when you find a higher score.
Show solution
def main(): var scores: List[Tuple[String, Int]] = [("Ada", 91), ("Bo", 78), ("Cy", 95)] var best_name = String("") var best_score = -1 for name, score in scores: if score > best_score: best_name = name best_score = score print(best_name, "wins with", best_score)Output:
Cy wins with 95Starting best_score at -1 means the first real score always replaces it.
3. Fix the program
Section titled “3. Fix the program”This program should print both values of the pair. It doesn’t compile. Fix it.
def main(): var pair = ("width", 20) for i in range(2): print(pair[i])Hint: a tuple index must be a number written in the code.
Show solution
def main(): var pair = ("width", 20) var label, size = pair print(label) print(size)Output:
width20A tuple can’t be indexed with a loop variable, because each position can have a different type. Unpacking (or writing pair[0] and pair[1]) works.
- A tuple is a fixed group of values that can have different types:
var t = ("Ada", 36). - Its type is written
Tuple[String, Int]. A one-value tuple needs a comma:(7,). - Read values with
t[0],t[1]. The index must be a fixed number, and you can’t loop over a tuple. - Unpack with
var a, b = t, and swap witha, b = b, a. - Return several values from a function with
-> Tuple[A, B]andreturn a, b. - Unlike Python, you can change a value in a
vartuple, but not its size or types.
Next up: Optional, Mojo’s way of saying “a value, or nothing at all”.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Tuple API docs: the
Tupletype and what it supports. - Mojo manual: Types: the official short introduction to tuples.
- Expression reference: the exact rules for tuple expressions and parentheses.
- Mojo manual: Functions: more on return types, including returning tuples.