Finding a value in a list
The function in Listing 1 performs a linear search: it checks items in order and returns the zero-based index of the first match. If the value is absent, it returns -1.
find_first_index that receives a list and a value as arguments and returns the zero-based index of the first match, or -1 if no match exists (Question 1).
def find_first_index(values: list[int], value: int) -> int:
for i in range(len(values)):
if values[i] == value:
return i # Stop at the first match.
return -1 # No match was found.
def main() -> None:
arr: list[int] = [1, 2, 0, 4, 5, 0, 0, 0, 0, 0, 0]
print(find_first_index(arr, 5))
# Run the example when this file is executed.
if __name__ == "__main__":
main()What does the listing print?
45-10
TipHint
len(items)returns the number of items, without changing the collection.len([8, 3])is2;len([])is0. For nested lists, it counts the outer items only.range(start, stop, step)supplies integers fromstarttoward, but excluding,stop.stepdefaults to1, andrange(stop)starts at0.list(range(2, 7, 2))is[2, 4, 6];list(range(5, 1, -2))is[5, 3].- A range is empty when the step cannot reach the stop; a zero step raises
ValueError.
listcollects the supplied values in a new list.