Modifying a List While Iterating
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]:Ais removed,Bis skipped,Cis 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
- A
forloop over a list does not walk a linked structure. What does the list iterator actually store between steps? - After
jobs.remove(A), what is now at index 0, and what index will the iterator look at next? - 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
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.