Skip to content

Mojo Span

A Span is a view into values that live somewhere else, like a window onto part of a list. It doesn’t own anything and doesn’t copy anything: it just knows where the values start and how many there are. You’ll use spans mostly as function arguments, so one function can work on a List, an Array, or just a slice of either. You’ve already made spans without noticing: my_list[1:3] gives you one.

Say you write a function that adds up numbers. If it takes a List[Int], you can’t pass it an array, and you can’t pass it “just the first three items” without building a new list first. A Span fixes both:

def total(nums: Span[Int, _]) -> Int:
var sum = 0
for n in nums:
sum += n
return sum
def main():
var scores: List[Int] = [10, 20, 30, 40]
var fixed = [1, 2, 3]
print(total(scores))
print(total(fixed))
print(total(scores[1:3]))

Output:

100
6
50

One function, three kinds of input: a whole list, a whole array, and a slice of a list. Mojo turns a List or an Array into a Span for you when a function asks for one. Nothing is copied: the span looks straight at the original values.

A span needs to know two things in its type: the element type (Int), and where the data lives, which Mojo calls its origin. The origin is how the compiler makes sure the data is still there while the span is in use. You’ll learn about origins later, in the Ownership lessons.

In a function argument, you don’t know the origin, because it depends on the caller. The _ says “fill it in from whatever I’m given”. If you leave it out, Mojo tells you:

def total(nums: Span[Int]) -> Int:
return len(nums)
def main():
var scores: List[Int] = [10, 20]
print(total(scores))
span.mojo:1:21: error: 'Span' failed to infer parameter 'origin', specify the parameter or use '_' or '...' to unbind the parameter explicitly
def total(nums: Span[Int]) -> Int:
^
mojo: error: failed to parse the provided Mojo source module

So the rule of thumb is simple: write Span[Int, _] for a read-only span argument.

Slicing a List or an Array with start:end gives you a span. You can index it, loop over it, ask its length, and slice it again:

def main():
var letters: List[String] = ["a", "b", "c", "d", "e"]
var middle = letters[1:4]
print(middle)
print(len(middle))
var smaller = middle[0:2]
print(smaller)

Output:

[b, c, d]
3
[b, c]

smaller is a view into a view, and it still points at the original letters list. You can also make a span of a whole list with Span(letters).

A span can also let you change the values it points at. To ask for that in a function, write mut=True:

def double_all(nums: Span[mut=True, Int, _]):
for i in range(len(nums)):
nums[i] *= 2
def main():
var prices: List[Int] = [3, 5, 8, 10]
double_all(prices)
print(prices)
double_all(prices[0:2])
print(prices)

Output:

[6, 10, 16, 20]
[12, 20, 16, 20]

The second call only doubles the first two items, because it only gets a view of them. This is how you write a function that works on part of a list in place.

Spans also have a few handy methods of their own, such as fill():

def main():
var board: List[Int] = [7, 7, 7, 7, 7]
var tail = board[2:]
tail.fill(0)
print(board)

Output:

[7, 7, 0, 0, 0]

fill(0) set every value in the view to 0, and since the view looks into board, it’s board that changed. The Span API docs list the other methods, like swap_elements() and binary_search_by().

A span points at someone else’s values, so what happens if those values move? A List stores its items in a block of memory, and when it grows, it may move them to a new, bigger block. An old span would then point at nothing. Mojo catches this at compile time:

def main():
var scores: List[Int] = [10, 20, 30]
var first_two = scores[0:2]
scores.append(40)
print(first_two)
span.mojo:5:11: error: use of invalidated interior reference 'scores["element"]'
print(first_two)
^
span.mojo:4:18: note: origin was invalidated here
scores.append(40)
^
mojo: error: failed to run the pass manager

The message says that append invalidated the span, and points to the line where it happened. The fix is to make the span after you’re done changing the list’s size, or to use it before. This kind of mistake causes crashes in C and C++. In Mojo, it doesn’t compile. The Mojo manual’s page on lifetimes and origins explains how this works.

When you need to keep the values, or change them without touching the original, copy the span into a new List:

def main():
var temps: List[Int] = [12, 19, 7, 23, 15]
var week_start = List[Int](temps[0:3])
week_start.append(99)
print(week_start)
print(temps)

Output:

[12, 19, 7, 99]
[12, 19, 7, 23, 15]

List[Int](span) copies the values. The new list is separate, so temps stays as it was.

Once you know about spans, you’ll notice them in a lot of places:

  • The built-in sort() function takes a span, which is why you can sort a whole list or just a slice of it. See Mojo Sorting & Searching.
  • String.as_bytes() gives you a Span[UInt8, ...] over the bytes of a string. See Mojo Strings in Depth.
  • String methods like split() and strip() return StringSpan values, the text version of the same idea: views into the original string.

Python’s closest relative is memoryview, which you may never have needed. In Python, slicing a list (xs[1:3]) always makes a new list. In Mojo, xs[1:3] is a cheap view, and you call List[Int](xs[1:3]) when you want a real copy.

Python Mojo
xs[1:3] A new list A Span (view), no copy
Change the slice Doesn’t affect xs Changes xs (through a mutable span)
Keep a copy xs[1:3] List[Int](xs[1:3])
Function for lists and arrays Duck typing Take a Span[T, _]

Write average(nums: Span[Int, _]) -> Float64. Use it to print the average of a whole list [4, 8, 6, 2] and of its last two items.

Hint: the last two items are nums_list[2:].

Show solution
def average(nums: Span[Int, _]) -> Float64:
var sum = 0
for n in nums:
sum += n
return Float64(sum) / Float64(len(nums))
def main():
var nums: List[Int] = [4, 8, 6, 2]
print(average(nums))
print(average(nums[2:]))

Output:

5.0
4.0

The same function handles the full list and the slice, and neither call copies any numbers.

Write clamp(nums: Span[mut=True, Int, _], high: Int) that lowers every value above high to high. Call it on [3, 15, 7, 22] with high = 10.

Hint: loop over range(len(nums)) and assign to nums[i].

Show solution
def clamp(nums: Span[mut=True, Int, _], high: Int):
for i in range(len(nums)):
if nums[i] > high:
nums[i] = high
def main():
var values: List[Int] = [3, 15, 7, 22]
clamp(values, 10)
print(values)

Output:

[3, 10, 7, 10]

mut=True makes the span writable, so assigning to nums[i] changes values in main.

This program doesn’t compile. Make it print the first two names and then the full list with "Cy" added.

def main():
var names: List[String] = ["Ada", "Bo"]
var view = names[0:2]
names.append("Cy")
print(view)
print(names)

Hint: append invalidates the view. Use the view before the list changes.

Show solution
def main():
var names: List[String] = ["Ada", "Bo"]
var view = names[0:2]
print(view)
names.append("Cy")
print(names)

Output:

[Ada, Bo]
[Ada, Bo, Cy]

After the append, view isn’t used any more, so there’s nothing left to go wrong. You could also copy the view into a List first.

  • A Span is a view into values that live in a List, an Array or another span. It doesn’t own or copy anything.
  • Take Span[Int, _] in a function to accept lists, arrays and slices. The _ lets Mojo fill in the origin.
  • Use Span[mut=True, Int, _] when the function should change the values.
  • Slicing with xs[a:b] gives you a span, and you can slice a span again.
  • Mojo won’t compile code that uses a span after its list was resized.
  • List[Int](span) makes a real, separate copy.

Next up: sorting and searching, putting lists in order and finding things in them.

Quick check

1. What does my_list[1:3] give you in Mojo?
2. Which argument type accepts a List[Int], an Array of Int and a slice of either?
3. Why does Mojo reject using a span after my_list.append(...)?
4. How do you get a separate copy of the values in a span?