Skip to content Skip to sidebar Skip to footer

What Are Python Generators?

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 w

Solution 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.

Solution 2:

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

Solution 3:

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.

Solution 4:

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.

Post a Comment for "What Are Python Generators?"