Curriculum

Curriculum

Handle an Empty List Without Crashing

Scenario

A campus dashboard summarizes today’s room requests: requests = [].

Selected choicePick a choice below
Result—

Try it yourself

Compare how counting, filtering, and first-element lookups behave on an empty list.

Reveal the explanation
  1. Count matching items in []

    Returns 0 cleanly because the accumulator starts at 0 and the loop runs 0 times.

  2. Collect open rooms from []

    Returns [] cleanly (an empty result list, never an error).

  3. 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.

Review first
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

Why is accessing items[0] unsafe before checking if items is empty?
Show the answer and reasoning

Correct answer An empty list has no index 0, causing IndexError/panic or undefined

Checking length == 0 before indexing prevents out-of-bounds crashes.