Problem solving · must-tier · asked at Amazon, Apple, Google, Meta, Microsoft, Netflix

Modifying a List While Iterating

easydebugging

Problem

A scheduler keeps a list of in-flight jobs and periodically removes the ones that have finished:

class Job:
    def __init__(self, name: str, finished: bool = False):
        self.name = name
        self.finished = finished


def purge_finished(jobs: list[Job]) -> None:
    for job in jobs:
        if job.finished:
            jobs.remove(job)

Symptom: after a purge, finished jobs are sometimes still in the list. It never happens when finished jobs are scattered, and it always happens when two finished jobs sit next to each other. No exception is raised. Explain the exact pattern of which jobs survive and fix the function without changing its signature (callers hold a reference to the list and expect it to be modified in place).

Examples

  • jobs = [A(done), B(done), C] → expected [C]. Actual [B, C]: A is removed, B is skipped, C is inspected.
  • jobs = [A(done), B, C(done)] → [B]. Correct, because no two finished jobs are adjacent.
  • jobs = [A(done), B(done), C(done), D(done)] → expected []. Actual [B, D]: every other finished job survives.

Hints

  1. A for loop over a list does not walk a linked structure. What does the list iterator actually store between steps?
  2. After jobs.remove(A), what is now at index 0, and what index will the iterator look at next?
  3. If you must edit the list in place, either iterate over something that does not change, or write the survivors back with a slice assignment.

Last reviewed 8 September 2026