Mojo Arrays
An Array is a collection with a fixed size that the compiler knows before your program runs. It can’t grow or shrink, but in return it’s simple and cheap: the values are stored right where the variable lives, with no extra memory allocated. You’ve already met arrays without knowing it, because a plain list literal like [1, 2, 3] in Mojo makes an Array, not a List. This lesson shows what that means and when it’s what you want.
A bare [1, 2, 3] is an Array
Section titled “A bare [1, 2, 3] is an Array”def main(): var days = [31, 28, 31] print(days) print(len(days)) print(days[0])Output:
[31, 28, 31]331It looks just like a list, and it prints like one. But the type of days is Array[Int, 3]: an array of Int values with exactly 3 of them. The size is part of the type.
The difference shows up as soon as you try to grow it:
def main(): var days = [31, 28, 31] days.append(30)array.mojo:3:9: error: 'Array[Int, Int(3)]' value has no attribute 'append' days.append(30) ~~~~^mojo: error: failed to parse the provided Mojo source moduleAn array has no append, pop or insert, because its size can never change. If you need those, ask for a list: var days: List[Int] = [31, 28, 31]. Mojo Lists covers that type.
Making arrays
Section titled “Making arrays”You can write the type yourself, or let Mojo build an array of a given size for you:
def main(): var names: Array[String, 2] = ["Ada", "Bo"] var counts = Array[Int, 5]() var ratios = Array[Float64, 3](fill=0.5) print(names) print(counts) print(ratios)Output:
[Ada, Bo][0, 0, 0, 0, 0][0.5, 0.5, 0.5]Array[String, 2]reads “an array of 2 strings”. The literal on the right must have exactly 2 values.Array[Int, 5]()makes 5 values that start at their default, which is0for numbers.Array[Float64, 3](fill=0.5)makes 3 values that all start as0.5.
The size must be known at compile time
Section titled “The size must be known at compile time”The size in Array[Int, 5] is a parameter: a value the compiler uses while it builds your program. That’s what the square brackets after a type mean in Mojo. So the size has to be a number written in the code, or a comptime constant:
comptime SLOTS = 4
def main(): var parking = Array[Bool, SLOTS](fill=False) parking[2] = True print(parking)Output:
[False, False, True, False]A normal variable won’t do, because its value only exists when the program runs:
def main(): var n = 4 var parking = Array[Bool, n](fill=False) print(parking)array.mojo:3:31: error: cannot use a dynamic value in a parameter list var parking = Array[Bool, n](fill=False) ^mojo: error: failed to parse the provided Mojo source moduleIf the size depends on input, a file or anything else you only know at run time, use a List. You’ll learn more about parameters in Mojo Parameters.
Reading and changing items
Section titled “Reading and changing items”Indexing works like with a list. Indexes start at 0, and you can change an item by assigning to it:
def main(): var temps = [12, 15, 9, 20] temps[2] = 11 print(temps) print(temps[len(temps) - 1]) print(15 in temps)Output:
[12, 15, 11, 20]20TrueLike lists, arrays don’t accept negative indexes, so the last item is temps[len(temps) - 1].
Because the compiler knows the size, it can catch some mistakes before the program runs. A fixed index that’s too big is a compile error:
def main(): var temps = [12, 15, 9, 20] print(temps[4])array.mojo:1:5: error: function instantiation faileddef main(): ^array.mojo:3:16: note: call expansion failed print(temps[4]) ^Mojo/stdlib/std/collections/array.mojo:781:9: note: constraint failed: index is out of boundsmojo: error: failed to run the pass managerWhen the index is in a variable, the check happens at run time instead, and the program stops with “index 4 is out of bounds, valid range is 0 to 3”. Either way, Mojo won’t read memory past the end of the array.
Looping over an array
Section titled “Looping over an array”for loops work the same as with a list, including ref for changing items in place:
def main(): var prices = [4, 10, 7] var total = 0 for p in prices: total += p print("total:", total)
for ref p in prices: p = p * 2 print(prices)Output:
total: 21[8, 20, 14]Arrays in functions
Section titled “Arrays in functions”When a function takes an array, its type includes the size. Array[Int, 3] only accepts arrays of exactly 3 values:
def total(nums: Array[Int, 3]) -> Int: var sum = 0 for n in nums: sum += n return sum
def main(): print(total([1, 2, 3]))Output:
6Calling total([1, 2, 3, 4]) is a compile error: “value passed to ‘nums’ cannot be converted from list literal to ‘Array[Int, Int(3)]’”. To accept arrays of any size, make the size a parameter of the function. This is a preview of Mojo Parameters, so don’t worry about the details yet:
def total[n: Int](nums: Array[Int, n]) -> Int: var sum = 0 for x in nums: sum += x return sum
def main(): print(total([1, 2, 3])) print(total([10, 20, 30, 40, 50]))Output:
6150[n: Int] tells Mojo “work out n from whatever array you’re given”. Another way to accept any size is to take a Span, a view that works for both arrays and lists. That’s the next lesson: Mojo Span.
Copying an array
Section titled “Copying an array”An array is a value, and like a list it isn’t copied by a plain =. var b = a gives the “cannot be implicitly copied” error. Use .copy():
def main(): var a = [1, 2, 3] var b = a.copy() b[0] = 100 print(a, b)Output:
[1, 2, 3] [100, 2, 3]Grids: arrays of arrays
Section titled “Grids: arrays of arrays”An array can hold other arrays, which gives you a small fixed grid:
def main(): var board = [[0, 0, 0], [0, 0, 0]] board[1][2] = 5 for row in board: print(row) print(len(board), "rows,", len(board[0]), "columns")Output:
[0, 0, 0][0, 0, 5]2 rows, 3 columnsboard is an Array[Array[Int, 3], 2]: 2 rows, each an array of 3 numbers. board[1][2] means row 1, column 2.
Array or List?
Section titled “Array or List?”Array[T, n] |
List[T] |
|
|---|---|---|
| Size | Fixed, part of the type | Grows and shrinks |
| Known when? | At compile time | At run time |
| Memory | Stored inline, no heap allocation | Allocates memory as it grows |
append, pop |
No | Yes |
| Literal | [1, 2, 3] |
var xs: List[Int] = [1, 2, 3] |
Pick an array when the size is truly fixed by the problem: the 7 days of a week, the 3 parts of an RGB color, a 3 by 3 game board. Pick a list for everything else, which in everyday code is most of the time. The Mojo types reference describes Array as a “fixed-size array stored inline, with no heap allocation”, which is why it’s a good fit for small, fixed data.
If you have an array and need a list, List[Int](my_array) copies the values into a new list.
Practice
Section titled “Practice”1. Week of steps
Section titled “1. Week of steps”Make an Array[Int, 7] filled with 0. Set day 0 to 4000, day 3 to 9000 and day 6 to 6500. Print the array and the total number of steps.
Hint: Array[Int, 7](fill=0), then a for loop to add them up.
Show solution
def main(): var steps = Array[Int, 7](fill=0) steps[0] = 4000 steps[3] = 9000 steps[6] = 6500 var total = 0 for s in steps: total += s print(steps) print("total:", total)Output:
[4000, 0, 0, 9000, 0, 0, 6500]total: 19500The week always has 7 days, so a fixed-size array is a natural fit here.
2. Largest of any size
Section titled “2. Largest of any size”Write largest[n: Int](nums: Array[Int, n]) -> Int that returns the biggest value. Call it with [3, 9, 2] and with [7, 1, 8, 8, 4].
Hint: start with nums[0] and compare each item with it.
Show solution
def largest[n: Int](nums: Array[Int, n]) -> Int: var best = nums[0] for x in nums: if x > best: best = x return best
def main(): print(largest([3, 9, 2])) print(largest([7, 1, 8, 8, 4]))Output:
98Mojo works out n from each call (3, then 5), so one function handles both sizes.
3. Fix the program
Section titled “3. Fix the program”This program should collect the numbers 1 to 5. It doesn’t compile. Fix it.
def main(): var nums = [] for i in range(1, 6): nums.append(i) print(nums)Hint: which collection can grow?
Show solution
def main(): var nums = List[Int]() for i in range(1, 6): nums.append(i) print(nums)Output:
[1, 2, 3, 4, 5]The values are added one at a time while the program runs, so you need a List. An empty [] with no type isn’t allowed anyway, because Mojo can’t tell what it should hold.
Array[T, n]holds exactlynvalues of typeT. The size is part of the type and never changes.- A bare literal
[1, 2, 3]makes anArray. WriteList[Int]when you need a list. - The size must be known at compile time: a number in the code or a
comptimeconstant. - Make arrays with a literal,
Array[Int, 5]()(defaults) orArray[Int, 5](fill=x). - Index, loop,
inandfor refwork like on a list. There’s noappend, no negative indexes, and a fixed index that’s too big is a compile error. - Use an array for small data with a fixed size, and a list for everything else.
Next up: Span, a view into a list or an array that lets functions read data without copying it.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Array API docs: every way to create and use an
Array. - Mojo types reference: a short table of all built-in collection types.
- Mojo manual: Parameterization: how compile-time parameters like an array’s size work.
- Mojo manual: Types: the official introduction to collections.