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
ArrayListcount their structural modifications. The iterator remembers the count it started with and checks it on eachnext(). If it changed, you get aConcurrentModificationExceptionright away instead of a subtly wrong result. The one sanctioned way to remove during iteration is the iterator's ownremove()method. - Python lets you do it. Changing a
listinside aforloop 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 aRuntimeError.)
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:
ConcurrentModificationException — Java's fail-fast behaviour, and why it is only a best-effort check.
Fail-fast system — the design principle behind throwing early instead of continuing with bad state.