Mojo Tuples

A tuple groups a fixed number of values of potentially different types into one unit. Unlike a list, a tuple does not change after creation — you cannot add, remove, or replace its elements. Tuples are ideal for returning multiple values from a function or grouping related data that should not change.

Tuple vs List

          Tuple                    List
  ┌───────────────────┐    ┌─────────────────────┐
  │  ("Alice", 30)    │    │  ["Alice", "Bob"]   │
  │  Fixed count: 2   │    │  Grows/shrinks      │
  │  Can mix types    │    │  Same type per List │
  │  Cannot modify    │    │  Can modify         │
  └───────────────────┘    └─────────────────────┘

Creating Tuples

fn main():
    var point = (10, 20)            # two integers
    var person = ("Alice", 30)      # string + integer
    var rgb = (255, 128, 0)         # three integers

    print(point)    # (10, 20)
    print(person)   # ('Alice', 30)
    print(rgb)      # (255, 128, 0)

Accessing Tuple Elements

Access elements by index just like a list, starting from zero.

fn main():
    var location = ("Tokyo", 35.6895, 139.6917)

    var city      = location[0]   # "Tokyo"
    var latitude  = location[1]   # 35.6895
    var longitude = location[2]   # 139.6917

    print(city, latitude, longitude)
  location tuple:
  Index:    0         1          2
          "Tokyo"  35.6895  139.6917
             ↑
          city = location[0]

Tuple Unpacking

Unpacking assigns each element of a tuple to a separate variable in one statement. It makes code much more readable than indexing manually.

fn main():
    var dimensions = (1920, 1080)

    var width, height = dimensions
    print("Width:", width)    # Width: 1920
    print("Height:", height)  # Height: 1080
Unpacking Diagram:
  (1920, 1080)
   /         \
width       height
1920        1080

Unpacking in a Loop

fn main():
    var scores = [(("Alice", 95), ("Bob", 87), ("Carol", 92))]

    var a_name, a_score = ("Alice", 95)
    var b_name, b_score = ("Bob", 87)
    print(a_name, "scored", a_score)   # Alice scored 95
    print(b_name, "scored", b_score)   # Bob scored 87

Returning Multiple Values from Functions

Tuples are the standard way to return multiple results from a Mojo function.

fn stats(a: Int, b: Int, c: Int) -> (Int, Int, Int):
    var total = a + b + c
    var minimum = a
    var maximum = a

    if b < minimum: minimum = b
    if c < minimum: minimum = c
    if b > maximum: maximum = b
    if c > maximum: maximum = c

    return (total, minimum, maximum)

fn main():
    var total, low, high = stats(12, 5, 20)
    print("Sum:", total)    # 37
    print("Min:", low)      # 5
    print("Max:", high)     # 20
Function returns one tuple:  (37, 5, 20)
Unpacking assigns three vars: total=37, low=5, high=20

Tuples as Dictionary Keys

Because tuples are immutable and have a consistent identity, they work as dictionary keys. Lists cannot serve as dictionary keys because they can change.

fn main():
    # We store grid cell labels using (row, col) tuples as keys
    var cell_00 = (0, 0)
    var cell_01 = (0, 1)

    # Think of this as labeling grid positions
    print("Cell at row 0, col 0:", cell_00)
    print("Cell at row 0, col 1:", cell_01)

Nested Tuples

Tuples can contain other tuples, building hierarchical data structures.

fn main():
    var line_segment = ((0, 0), (5, 3))   # start and end points

    var start = line_segment[0]
    var end   = line_segment[1]

    print("Start:", start[0], start[1])   # Start: 0 0
    print("End:  ", end[0],   end[1])     # End:   5 3
Nested Tuple Structure:

  line_segment
       │
  ┌────┴────┐
  │         │
(0, 0)   (5, 3)
  │   │    │   │
  0   0    5   3

Single-Element Tuples

A tuple with one element needs a trailing comma. Without it, Mojo treats the parentheses as ordinary grouping, not a tuple.

fn main():
    var single = (42,)    # tuple with one element
    var not_tuple = (42)  # just the integer 42

    print(single[0])      # 42
    print(not_tuple)      # 42

Comparing Tuples

Mojo compares tuples element by element from left to right, stopping at the first difference.

fn main():
    var a = (1, 5)
    var b = (1, 8)
    var c = (2, 0)

    print(a == b)   # False — second elements differ (5 ≠ 8)
    print(a == (1, 5))   # True — all elements match

When to Use a Tuple

Situation                          | Use Tuple
-----------------------------------|----------
Return (x, y) from a function      | Yes
Store (name, age) that won't change| Yes
A collection that grows over time  | No — use List
Mixing types in one group          | Yes
Needing to sort or rearrange       | No — use List

Key Takeaways

Tuples group a fixed number of possibly different-typed values. Access elements by index. Use tuple unpacking to assign elements to named variables in one statement. Functions use tuples to return multiple results cleanly. Tuples are immutable — that makes them safe dictionary keys and reliable data carriers. A single-element tuple requires a trailing comma.

Leave a Comment

Your email address will not be published. Required fields are marked *