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.

Listing 1: A Python function 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?

  1. 4
  2. 5
  3. -1
  4. 0
  • len(items) returns the number of items, without changing the collection. len([8, 3]) is 2; len([]) is 0. For nested lists, it counts the outer items only.
  • range(start, stop, step) supplies integers from start toward, but excluding, stop.
    • step defaults to 1, and range(stop) starts at 0.
    • 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.
  • list collects the supplied values in a new list.