Search in a list

Finds a number in a list: the first position and how many times it is there. Teaches linear search and the index.

Open in Tokbit Level: Intermediate. Free in the browser, nothing to install, no account needed.

Run the example in Tokbit and step through it: before each step say what will happen and check it in the Variables panel. Then change it your way.

Flowchart

Flowchart of the Search in a list example

Python program

The same program as Python code. In Tokbit you see it when you switch from Diagram to Python above the flowchart.

"""Finds a number in a list: the first position and how many times it is there. Teaches linear search, the index and while with two conditions."""
numbers: list[int] = [4, 8, 15, 16, 23, 42, 8, 4]
target: int
# -1 means “not found yet”.
position: int = -1
count: int = 0
i: int = 0
print("List:", numbers)
target = int(input("Number to find:"))
# Linear search: goes from the start and stops at the first match.
while i < len(numbers) and position == -1:
    if numbers[i] == target:
        position = i
    i = i + 1
# Count of matches: goes through the whole list.
for j in range(len(numbers)):
    if numbers[j] == target:
        count = count + 1
if position == -1:
    print("The number", target, "is not in the list.")
else:
    print("First found at position", position, "(counting from 0).")
    print("Number of matches:", count)

Follow-up tasks

Tasks in which you change the example (with a model solution):

All examples