← Back

Home β€Ί Problems β€Ί Looping one step too far

Looping one step too far

πŸ› Fix the bug Topic: lists Difficulty: easy Free

What this problem practises

Lists are mutable and assigned by reference. That one fact explains most list bugs: aliasing between what look like "copies", append() and sort() returning None, and slice boundaries that disagree with the index arithmetic.

This is a fix-the-bug problem: a short program is given in its broken state, and the task is to repair the code so it produces the required output. The interactive editor runs your fixed version in the browser and checks it for you β€” no setup, no local interpreter.

Difficulty: easy β€” the fix or the trick is normally a single line, and a careful read should be enough.

The challenge

This should print every item in the list, but crashes partway through. Fix it.

The code runs in PyDebug’s in-browser compiler. Open the problem, run the snippet, watch the exact error or output, and keep iterating until it is right. Signed-in solves count toward XP and your daily streak.

The error it raises

Run the broken snippet and Python stops with this exact error: IndexError: list index out of range. Match it to the Python errors guide, then repair the line that produced it β€” knowing the message is half the fix.

The snippet

The interactive editor pre-fills exactly this code, broken and ready to repair:

fruits = ["apple", "banana", "cherry"]
for i in range(4):
    print(fruits[i])

Understand the rule

This program crashes with IndexError because its loop asks for one more position than the list owns β€” the classic result of range(len(items) + 1) or a while-loop condition using <= instead of <. Every pass before the last one works perfectly, which is what makes this bug sneaky: the crash appears at the end of the run, far from the line that caused it.

How to trace it

  1. Note the index printed in the traceback and compare it with len(list); an index equal to the length is the giveaway.
  2. Find where the loop's upper bound is computed and check for a stray + 1 or a <= where < belongs.
  3. Dry-run only the final iteration by hand: substitute the last value the loop variable will take.
  4. Confirm the fix by testing with a one-element and an empty list, the two sizes where boundary bugs hide.

Common wrong fixes

Rule to remember

range(len(items)) is already the exact set of valid indexes. Adding 1 to it, or using <= len(items) in a while loop, always reads one slot past the end.

Solve it in the interactive editor β†’

πŸ” Learning path: Loops

Problem 6 of 16 in this path. Work them in order β€” each one builds on the rule before it.

← Previous problemNext in path: Next problem β†’

More lists problems

Keep going