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
inanswers whether a value is present at all.index_ofwalks the positions withrange(len(values)).- Returning
-1signals that nothing matched.
Keywords and builtins used here
IntListdefforifindex_oflenmainprintrangereturnvar
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.
Step 5 of 6 in Collections, step 16 of 26 in Language basics.