Jump to content

Generator (computer programming)

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Jorend (talk | contribs) at 03:04, 3 April 2004. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

In computer science, particularly in the Python programming language, a generator is a special type of continuation that can be used as an iterator.

An example Python generator:

   def sums(n, min=1):
       if n == 0:
           yield []
           return
       elif n >= min:
           for i in range(min, n+1):
               for sol in sums(n-min, i):
                   yield [i] + sol

In Python, a generator can be thought of as an iterator that contains a frozen function call. Whenever the iterator's next() method is called, the frozen function call resumes where it was left off and runs until it reaches a yield statement. Then the function call is frozen again, the iterator spits out the yielded value, and execution continues with the iterator's caller.

Generators can be used to loop through the values of a list lazily. This is useful when only the first few items of the list are likely to be needed, and calculating the entire list would be costly or impractical.