LOGBOOK

HELP

Quiz Entry - updated: 2026.09.29

Can you modify a collection while an iterator is running over it, in Python and in Java?

Python: yes, a list can be changed during iteration without an error. Java: no, the standard collections detect the change and the iterator throws a ConcurrentModificationException.

The problem is the same in both languages: the iterator holds a position (an index, a node reference) that was valid for the collection as it was. Adding or removing elements underneath it can make that position point at the wrong element or skip one.

  • Java's answer is to fail fast. Collections such as ArrayList count their structural modifications. The iterator remembers the count it started with and checks it on each next(). If it changed, you get a ConcurrentModificationException right away instead of a subtly wrong result. The one sanctioned way to remove during iteration is the iterator's own remove() method.
  • Python lets you do it. Changing a list inside a for loop does not raise an error. The loop simply continues with its internal index against the modified list, so removing elements typically makes it skip the one after each removal. (Dicts and sets are stricter: changing their size during iteration raises a RuntimeError.)

Tip: in both languages the safe pattern is the same: iterate over a copy, or build a new collection instead of editing the one you are looping over.

Go deeper:

From Quiz: ADS / Linear Data Structures: Lists, Stacks, Queues, Deques, Iterators | Updated: Sep 29, 2026