Programming from zero

Count how many times a value appears in a list

easyLists

Problem statement

Counting matches uses the same accumulator idea as adding up disk usage: start a counter at 0 before the loop, then add 1 each time an item matches. The important part is that the += 1 sits inside the if, so it only runs on a match.

Common mistake: counting every item instead of only the matches.

TEXT
Wrong:
for code in codes:
count += 1
if code == target:
print("found one")

Here count += 1 runs on every pass, whether or not the item matches, so count ends up as the length of the list. It belongs inside the if.

Your task: given status codes [200, 500, 200, 404, 500, 200], count how many times 200 appears and print the count.

Expected output:

TEXT
3

Approach

Set count to 0, loop through the codes, and add 1 whenever a code equals the target. Python also has a built-in shortcut, codes.count(200), which does the same job. Write the loop first so you understand what it does.

DSA connection: counting how often values appear is called frequency counting, a very common first step in DSA problems.

codes = [200, 500, 200, 404, 500, 200]
target = 200
count = 0
for code in codes:
    if code == target:
        count += 1
print(count)