typestar

List literals in Mojo

Square brackets build a List, and the element type follows.

def main():
    var primes = [2, 3, 5, 7, 11]
    var ratios = [0.5, 1.5, 2.5]
    # Type a String list explicitly; bare literals infer StringSlice.
    var names: List[String] = ["ada", "grace", "alan"]
    print(len(primes), primes[0], primes[len(primes) - 1])
    print(ratios[1])
    for name in names:
        print(name)

How it works

  1. [2, 3, 5, 7, 11] infers List[Int] from its contents.
  2. String lists need the explicit List[String] annotation.
  3. There is no negative indexing, so the last item is xs[len(xs) - 1].

Keywords and builtins used here

The run, in numbers

Lines
9
Characters to type
290
Tokens
83
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 59 seconds.

Type this snippet

Step 1 of 6 in Collections, step 12 of 26 in Language basics.

← Previous Next →