Skip to content
BENIBIX Learn

Iterator vs Generator

An iterator is any object that gives items one at a time. A generator is a short way to write one: a function that pauses at each yield.

Development🧭 Programming Paradigms

Iterator

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

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
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.
Full entry
Development🧭 Programming Paradigms

Generator (Programming)

A function that pauses at each yield and hands out one value at a time.

A generator is a function that hands out values one at a time with the word yield. Each time it yields, it pauses and keeps its place. When the next value is asked for, it carries on from there. Python uses yield in a normal def. JavaScript marks a generator with function*. A generator is a quick way to make an iterator.

Example
Emma needs a million ticket numbers. A generator makes each one only when asked. So they never all sit in memory at once.
Why it matters
It saves memory, because values are made only when needed. It can even describe a list with no end.
Full entry

In one line

Iterator
An object that hands out items one at a time, each time you ask.
Generator (Programming)
A function that pauses at each yield and hands out one value at a time.