Skip to content
BENIBIX Learn

Iterator

Development🧭 Programming ParadigmsAsynchronous Code

Also known as Iterators, Iterable, Iterator Protocol

An object that hands out items one at a time, each time you ask.

Think of it like

It is like a bookmark in a book. It always knows which page comes next.

Example

Jack reads a huge log file line by line with an iterator. Only one line is in memory at a time.

Why it matters

It lets one loop work over many kinds of collection. It also lets you walk through data too big to load at once.

Definition

An iterator is an object that hands out the items of a collection one at a time. Each call to next gives the next item. When there are no more, it says it is done. A for loop uses an iterator behind the scenes. Lists, strings and files can all be stepped through this way.

Example code

python
it = iter(["apple", "pear"])
print(next(it))  # apple
print(next(it))  # pear
next(it)         # StopIteration
Each next() gives one item. After the last, it signals it is done.
The iterator's pointer moves one step on each call to next.

Common mistake

Looping over the same iterator twice. Once it is used up, it gives nothing the second time.

Key takeaways

  1. 1
    One at a time. Each call gives the next item.
  2. 2
    Knows its place. It remembers where it stopped.
  3. 3
    Runs out. Most cannot be rewound.

Compare