Handle an Empty List Without Crashing
Scenario
A campus dashboard summarizes today’s room requests: requests = [].
Try it yourself
Compare how counting, filtering, and first-element lookups behave on an empty list.
| Case | Result |
|---|---|
| Count matching items in [] | Select a choice above to see what happens. |
| Collect open rooms from [] | Select a choice above to see what happens. |
| Read requests[0] without checking length | Select a choice above to see what happens. |
Reveal the explanation
- Count matching items in []
Returns 0 cleanly because the accumulator starts at 0 and the loop runs 0 times.
- Collect open rooms from []
Returns [] cleanly (an empty result list, never an error).
- Read requests[0] without checking length
Unsafe! Crashes in Python/Go or returns undefined in JS. Check length == 0 first.
Counts return 0, filters return [], and lookups for a "first" or "average" item must guard against length == 0 before indexing or dividing.
Download shared test cases
Your turn
State the safe empty-list output for: (1) countOpenRooms([]), (2) promoteWaitlist([], 2), and (3) averageScore([]).
Common mistake Dividing total by 0 in averageScore([]) instead of guarding empty input first.
Check your work
countOpenRooms -> 0; promoteWaitlist -> []; averageScore([]) -> INVALID_EMPTY_SCORES (or explicit null).
Quick check
This browser could not save your progress. Changes last until you leave the page.