typestar

Searching a list in Mojo

A membership test and a hand-rolled index scan.

def index_of(values: List[Int], target: Int) -> Int:
    for i in range(len(values)):
        if values[i] == target:
            return i
    return -1

def main():
    var values = [4, 8, 15, 16, 23, 42]
    print(15 in values, 99 in values)
    print("16 sits at", index_of(values, 16))
    print("99 sits at", index_of(values, 99))

How it works

  1. in answers whether a value is present at all.
  2. index_of walks the positions with range(len(values)).
  3. Returning -1 signals that nothing matched.

Keywords and builtins used here

The run, in numbers

Lines
11
Characters to type
291
Tokens
92
Three-star pace
80 tpm

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

Type this snippet

Step 5 of 6 in Collections, step 16 of 26 in Language basics.

← Previous Next →