Quiz Entry - updated: 2026.09.29
What is an iterator, and what is its central operation?
An iterator is an object that walks through a collection one element at a time; its central operation is next(), which returns the following element and advances the position.
The idea is to separate what you do with each element from how the collection is laid out. Code that uses an iterator says "give me the next one" until there are none left, and does not care whether the elements live in an array, a linked list or a tree.
Key points:
- One operation does the work:
next()returns the current element and moves on. There is also a way to detect the end, which differs by language (see the Python and Java card). - It keeps state. The iterator remembers where it is, for example an index into an array or a reference to the current node. That is why it is typically a separate object tightly bound to its collection.
- Easy for linear structures. For an array, the state is an index that increments. For a singly-linked list, it is a node reference that follows
next. Trees and hash tables need more elaborate iterators, but the interface stays the same.
Every for-each loop in Java (for (x : list)) and every for x in ... loop in Python is an iterator underneath.
Go deeper:
Iterator — the general concept, with examples across languages.
Iterator pattern — the design pattern behind it: traversal decoupled from the collection's structure.