Curriculum

Curriculum

Loop Over a List and Count Matches in Python

Scenario

Test count_open_rooms(seat_counts) in Python on empty, single-item, and mixed lists.

Selected choicePick a choice below
Result—
Python
def count_open_rooms(seat_counts: list[int]) -> int:
    open_rooms = 0
    for seats in seat_counts:
        if seats > 0:
            open_rooms += 1
    return open_rooms

assert count_open_rooms([]) == 0
assert count_open_rooms([1]) == 1
assert count_open_rooms([0, 2, 0, 1]) == 2

Try it yourself

Compare each fixture input to verify Python returns the exact expected count.

Reveal the explanation
  1. count_open_rooms([])

    0 — loop runs 0 times and returns initialized open_rooms = 0.

  2. count_open_rooms([1])

    1 — single last-seat room counts as open.

  3. count_open_rooms([0, 2, 0, 1])

    2 — counts rooms with 2 and 1 seats, ignores zeros.

Keep return aligned with the def body, not indented inside the for loop, and test empty [] before moving to multi-item lists.

Review first
Download shared test cases

Your turn

Write count_passing(scores) in Python using a for loop and add 3 assert lines for [], [60], and [59, 60, 85].

Common mistake Indenting return inside the for loop.

Check your work

assert count_passing([]) == 0; assert count_passing([60]) == 1; assert count_passing([59, 60, 85]) == 2.

Quick check

In Python, what does "for seats in [0, 3, 1]:" bind seats to on each pass?
Show the answer and reasoning

Correct answer The list values 0, then 3, then 1 directly

Python for-in loops iterate directly over each element value in order.