Card 09/ 09

RecapDifficulty: Advanced1 min

Recap: Iterator Pattern

Walk one item at a time without seeing the storage, and an iterator, once used, is empty.

Iterator lets code walk any collection one element at a time without knowing how it is stored.

  • Intent. Access the elements of an aggregate in sequence without exposing its representation.
  • Structure. The aggregate creates iterators; each iterator keeps its own position, so walks do not interfere.
  • In each language. __iter__ and __next__ in Python, Iterable and Iterator in Java, [Symbol.iterator]() and next() in TypeScript.
  • On demand. An iterator can fetch or compute each element only when it is asked, such as the next page of results from a server.
  • In Python. A generator is an iterator with the position kept for you, and the usual way to write one.
  • The trap. An iterator used up is empty; return a fresh one from __iter__, or turn it into a list once.
  • When not. A plain list that already has an iterator, or callers that need access by position.