2

Possible Duplicate:
What can you use Python generator functions for?

I tried to read about python generators but did not understand much about the concept as to what we can do with generators, I am new to python

please let me know Thank you

Community
  • 1
  • 1
daydreamer
  • 80,741
  • 175
  • 429
  • 691
  • You should start with coroutines & continuations to learn general ideas behind generators. http://en.wikipedia.org/wiki/Coroutine, http://en.wikipedia.org/wiki/Continuation – Andrew Sep 25 '10 at 21:50

4 Answers4

1

Simply put, a generator in Python is a function that can maintain state between values produced. Read this.

yassin
  • 6,241
  • 7
  • 33
  • 39
1

The presentation here explains generators very well:

http://www.dabeaz.com/generators/index.html

I have yet to find a use for the more advanced pipelining stuff, but I use the general technique all the time to parse logfiles.

AHM
  • 4,946
  • 32
  • 36
1

While Yassin's answer is completely correct, I would rather explain it differently: A generator is a function that returns multiple values over time, where each value is generated (and returned) when you ask for it.

poke
  • 339,995
  • 66
  • 523
  • 574
0

http://docs.python.org/tutorial/classes.html#generators Read this first.

Basically, generators are iterable objects. The magic word here is yield. Instead of using the return statement, you use yield, which doesn't stop the execution of a function, but returns something. In order for you to be able to consume what the generator returns, you have to iterate through it.

dekomote
  • 3,551
  • 1
  • 16
  • 13