Possible Duplicate:
Difference between Python Generators vs Iterators
Generators seem like big deal in Python, new features are added to them now and then and so on.
As far as I can see, instead generators you could always use an object with iterator interface. Is (usually) better conciseness the only benefit of generators or am I missing something?
Yes, iterators are a more general construct, and anything you could do with a generator could be done with an iterator.
However, generators are really nice tool to express certain ideas in a very clean and concise fashion, for which iterators would become cumbersome.
For example, here’s a simple function:
Nice and easy. Here’s the same thing as an iterator:
One is 5 lines, the other is 12. The generator expresses the iteration process very succintly, while the iterator obfuscates it with explictly-maintained state and boilerplate code.
A lot of Python’s philosophy is based around readability and simplicity. In keeping with this, I feel that generators offer a nicer interface for a broad class of tasks that would otherwise require iterators. Yes, iterators are more powerful, but the syntactic advantages of generators certainly can’t be overlooked.