Mojo Lists

A list stores multiple values in a single named container. The values sit in a fixed order and you access them by their position. Mojo's List type is a dynamic structure — it grows and shrinks as your program adds and removes items.

The Shelf Analogy

  A list is like a numbered bookshelf:

  Index:   0       1       2       3       4
         ┌───────┬───────┬───────┬───────┬───────┐
  Value: │  "A"  │  "B"  │  "C"  │  "D"  │  "E"  │
         └───────┴───────┴───────┴───────┴───────┘

  - Each slot has an index starting from 0
  - You can add new books or remove existing ones
  - The order of books is maintained

Creating a List

from collections import List

fn main():
    var fruits = List[String]("apple", "banana", "mango")
    print(fruits[0])   # apple
    print(fruits[1])   # banana
    print(fruits[2])   # mango

The type inside square brackets (String) tells Mojo what kind of values the list holds. All values in one List must share the same type.

Accessing and Modifying Elements

from collections import List

fn main():
    var scores = List[Int](70, 85, 90)

    # Read an element
    print(scores[1])   # 85

    # Modify an element
    scores[1] = 95
    print(scores[1])   # 95

List Length

from collections import List

fn main():
    var items = List[String]("pen", "pencil", "ruler")
    print(len(items))   # 3

Adding Elements

append()

Adds one element to the end of the list.

from collections import List

fn main():
    var colors = List[String]("red", "green")
    colors.append("blue")
    print(len(colors))    # 3
    print(colors[2])      # blue
Before: [red, green]
append("blue")
After:  [red, green, blue]
                     ↑
                  new item added here

Removing Elements

pop()

Removes and returns the last element by default, or the element at a specified index.

from collections import List

fn main():
    var nums = List[Int](10, 20, 30, 40)
    var last = nums.pop()     # removes and returns 40
    print(last)               # 40
    print(len(nums))          # 3

Iterating Over a List

from collections import List

fn main():
    var planets = List[String]("Mercury", "Venus", "Earth", "Mars")

    for i in range(len(planets)):
        print(i, planets[i])

Output:

0 Mercury
1 Venus
2 Earth
3 Mars

Common List Patterns

Finding the Largest Value

from collections import List

fn main():
    var temps = List[Int](23, 31, 18, 27, 35)
    var maximum = temps[0]

    for i in range(len(temps)):
        if temps[i] > maximum:
            maximum = temps[i]

    print("Hottest day:", maximum)   # 35
Scan Diagram:
  [23, 31, 18, 27, 35]
   ↑
  max=23
       ↑
      31 > 23 → max=31
           ↑
          18 > 31? No
               ↑
              27 > 31? No
                   ↑
                  35 > 31 → max=35
  Result: 35

Building a List with a Loop

from collections import List

fn main():
    var squares = List[Int]()
    for i in range(1, 6):
        squares.append(i * i)

    for i in range(len(squares)):
        print(squares[i], end=" ")   # 1 4 9 16 25

Nested Lists

A list can contain other lists, creating a two-dimensional structure like a grid or a table.

from collections import List

fn main():
    # A 2×3 grid stored as a list of lists
    var row0 = List[Int](1, 2, 3)
    var row1 = List[Int](4, 5, 6)

    # Access row 1, column 2 (value = 6)
    print(row1[2])   # 6
Grid Visualization:
         col0  col1  col2
  row0:  [  1    2    3  ]
  row1:  [  4    5    6  ]

  row1[2] = 6

Copying a List

Assigning one list variable to another does not create a second copy — both variables point to the same data. To make a true independent copy, use the copy constructor.

from collections import List

fn main():
    var original = List[Int](1, 2, 3)
    var copy = List[Int](original)   # true copy
    copy.append(99)

    print(len(original))   # 3 — unchanged
    print(len(copy))       # 4

Key Takeaways

A Mojo List stores ordered, typed, mutable values. Access elements by zero-based index. Use append() to add elements and pop() to remove them. Iterate over a list with a for loop using range(len(...)). Lists grow and shrink dynamically. Nested lists represent two-dimensional data. Always use the copy constructor to create an independent duplicate.

Leave a Comment

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