What Are Lists In Mojo?

Mojo lists provide powerful and commonly useful data structures. A list allows us to store multiple values in a single variable, so it can be easy to organize, manipulate, and access data.

Lists are versatile, dynamic, and beginner-friendly for us because we can store numbers, strings, or even a combination of different data types in a single list.

What is a List in Mojo?

A list is an ordered collection of elements, and each list element has a specific position called an index that starts from 0.

Lists are mutable, which means we can easily add, remove, or change elements after the list is created. Also, a list can contain duplicate values.

Simple list example:

var fruits: List[str] = ["Apple", "Banana", "Mango", "Orange"]
print(fruits)

Output:

["Apple", "Banana", "Mango", "Orange"]

How To Access a List Elements?

We can access list elements using the indexing method, like:

print(fruits[0])  # Apple
print(fruits[2]) # Mango

Here, we can use negative indexing, like accessing elements from the end of the list:

print(fruits[-1])  # Orange
print(fruits[-2]) # Mango

We can easily modify the list because lists are mutable. Let’s see the example of changing the elements:

fruits = ["Apple", "Banana", "Mango", "Orange"]

fruits[1] = "Blueberry"

fruits[1] = “Blueberry”. This is modifying the element at index 1 of the list.

  • Lists are zero-indexed, so:
    • fruits[0] → “Apple”
    • fruits[1] → “Banana” (this is what we are changing)
    • fruits[2] → “Mango”
    • fruits[3] → “Orange”

After the modification, the list becomes:

["Apple", "Blueberry", "Mango", "Orange"]

How To Add Elements To a List?

We can use two methods to add elements to a List, such as append() and insert().

  • append(): Use this method when you want to add an element at the end of the list.
  • insert(): When you want to insert an element at a specific position, you can use the insert() method.

For example:

fruits.append("Grapes")
print(fruits) # ["Apple", "Blueberry", "Mango", "Orange", "Grapes"]

fruits.insert(2, "Pineapple")
print(fruits) # ["Apple", "Blueberry", "Pineapple", "Mango", "Orange", "Grapes"]

In this code:

  • Append method added a grape to the end of the list.
  • The insert method inserted an element at a specific number, like a Pineapple.

How To Remove Elements Form a List?

We can remove elements by two methods: remove() and pop(). Both work differently, like:

  • The remove() method is used to remove a specific value.
  • The pop() method is used when you want to remove values by index.

See this simple example:

fruits.remove("Mango")
print(fruits) # ["Apple", "Blueberry", "Pineapple", "Orange", "Grapes"]

fruits.pop(1)
print(fruits) # ["Apple", "Pineapple", "Orange", "Grapes"]
  • First, we used remove() to delete mango from the list. And then we used a pop(1) with an index number to remove items by number.

How To Create List Slicing?

Slicing is a method that we can use to subset elements from a list. You can slice the elements easily by the following methods.

Syntax of the slicing:

list[start:end]
  • start is defined as the slicing begins (inclusive), and the end is used to stop the slicing (exclusive).

Example:

numbers: List[Int] = [10, 20, 30, 40, 50, 60]

print(numbers[1:4]) # [20, 30, 40]
print(numbers[:3]) # [10, 20, 30]
print(numbers[3:]) # [40, 50, 60]
  • Remember, slicing will always end -1 at the point.

Loop Through Lists

We can prints lists using the loop, like:

fruits = ["Apple", "Pineapple", "Orange", "Grapes"]

for fruit in fruits:
print("I like", fruit)

Output:

I like Apple
I like Pineapple
I like Orange
I like Grapes

Explanation of this code:

  • Fruits is a list of items
  • This line “for fruit in fruits” creates a for loop that goes through each element in the list one by one.
  • On the first loop, fruit = “Apple”
  • Second loop, fruit = “Pineapple”
  • Third loop, fruit = “Orange”
  • Fourth loop, fruit = “Grapes”
  • print(“I like”, fruit) → prints the string “I like” followed by the current fruit.

What Are The Operations in List?

We can also perform operations on a list for different scenarios. Mojo provides max() and min() methods to find values.

For example:

1. max()

max() used to find the largest value in a list. For example:

numbers = [1, 2, 3, 4, 5]
print(max(numbers)) # Output: 5
  • Here, 5 is the largest number, so max(numbers) returns 5.

2. min()

min() is used to find the smallest value in a list. For example:

numbers = [1, 2, 3, 4, 5]
print(min(numbers)) # Output: 1
  • Here, 1 is the smallest number, so min(numbers) returns 1.

Example of Lists Operations:

We use multiple operations in the list below.

numbers = [1, 2, 3, 4, 5]

# Sum of elements
var total = 0
for num in numbers:
total += num
print("Total:", total) # Total: 15

# Maximum and Minimum
print("Max:", max(numbers)) # Max: 5
print("Min:", min(numbers)) # Min: 1

Output of this example:

Total: 15
Max: 5
Min: 1

What Is The Nested Lists in Mojo?

A nested list is a list that contains other lists as its elements. This is very useful when you want to represent matrix-like data or any grouped data structure.

Example

matrix: List[List[Int]] = [[1, 2], [3, 4], [5, 6]]
  • matrix is a list of lists.
  • The first element is [1, 2], the second is [3, 4], and the third is [5, 6].
  • You can imagine it like a table with rows and columns:
Row 0: [1, 2]
Row 1: [3, 4]
Row 2: [5, 6]

Now, access these elements using two indices:

print(matrix[1][0])  # Output: 3
  • matrix[1] → accesses the second list, [3, 4] (remember indexing starts at 0).
  • [0] → accesses the first element of that list → 3.
  • So matrix[1][0] = 3.

Why nested lists Used?

Used nested lists because sometimes data is two-dimensional or even more, like grids, tables, or coordinates, and a single list can’t hold multiple rows of data easily. But a list of lists can do this, like:

matrix[row][column]
  • First index → row (which list you want)
  • Second index → column (which element in that list)
  • Loops with nested lists

You can use nested loops to go through all elements:

for row in matrix:
    for num in row:
        print(num)

Output:

1
2
3
4
5
6
  • The outer loop goes through each row (list).
  • The inner loop goes through each element inside that row. That’s why there is a loop inside a loop to handle nested structure.

Real-Life Example: Student Marks Management

Learn, this real-life example of Mojo Lists.

# List of student marks
marks: List[Float64] = [85.5, 92.0, 78.5, 88.0]

# Calculate average
var total: Float64 = 0
for mark in marks:
total += mark

average = total / len(marks)
print(f"Average Marks: {average}")

# Find top scorer
print(f"Top Score: {max(marks)}")

Output:

Average Marks: 86.0
Top Score: 92.0

Try to understand this code example by yourself and write it in your unique logic.

Student Exercise: “Weekly Expense Tracker”

Building a small program to help students track their daily expenses for a week.

Tasks:

  1. Create a list of 7 numbers, each representing the money spent on a day of the week.
  2. Print all the daily expenses.
  3. Calculate the total weekly expense.
  4. Find the day with the highest expense.
  5. Calculate the average daily expense.

Example Input (List Values):

expenses = [120, 85, 90, 150, 75, 200, 130]

Expected Output:

Daily Expenses: [120, 85, 90, 150, 75, 200, 130]
Total Weekly Expense: 850
Highest Expense: 200
Average Daily Expense: 121.43

Also Learn this Topics:

Leave a Comment