Programmer's Wiki

A generator is a method that iterates through a collection and returns its elements one at a time, as opposed to returning all of its elements at once.

Generators yield the values of the collection one at a time, functioning as an iterator over the collection. Programming languages usually implement this using a yield statement, so that the containing method returns an iterator. Whenever the yield statement is encountered, the method breaks and returns an item from the collection. When a signal to move to the next item is encountered, the method resumes starting from the previously broken yield statement. When the generator returns or ends, the iteration ends (there are no more items in the collection).

Generators can also be implemented using first-class continuations.

Languages which offer this feature include JavaScript 1.7, Python, and Ruby.


A simple generator for a linked list using a yield statement:

    current = list.head
         yield current.value
         current =

An implementation of a preorder traversal:

    if node is null then
        return {}
    for each item in iterator(node.left)
        yield item
    for each item in iterator(node.right)
        yield item
    yield node