What does the "yield" keyword do in Python?
pythongeneratorsiterablesyielditertools
Abstraction: Python yield keyword creates generator objects lazily
Key points:
yieldturns a function into a generator — calling the function returns a generator object without executing the body- Generators are iterators you can only iterate over once; values are computed on the fly, not stored in memory
- Execution resumes from where it left off each time
forcallsnext()on the generator - Generator exhaustion occurs when the function returns without hitting
yield(loop ends or condition fails) itertoolsmodule provides advanced generator utilities:permutations,chain,tee,izip, etc.- Duck typing means Python's
extend()and similar methods accept any iterable, including generators
Connections: Python · Generators · Lazy Evaluation · Iterators
Source: http://stackoverflow.com/questions/231767/the-python-yield-keyword-explained