flâneur — a map of the web's best reading

Difference between Python's Generators and Iterators - Stack Overflow

stackoverflow.com · 7,720 words · saved by 1 readers

What is the difference between iterators and generators? Some examples for when you would use each case would be helpful. iterator is a more general concept: any object whose class has a __next__ method (next in Python 2) and an __iter__ method that does return self. Every generator is an iterator, but not vice versa. A generator is built by calling a function that has one or more yield expressions (yield statements, in Python 2.5 and earlier), and is an object that meets the previous paragraph's definition of an iterator. You may want to use a custom iterator, rather than a generator, when you need a class with somewhat complex state-maintaining behavior, or want to expose other methods besides __next__ (and __iter__ and __init__). Most often, a generator (sometimes, for sufficiently simple needs, a generator expression) is sufficient, and it's simpler to code because state maintenance (within reasonable limits) is basically "done for you" by the frame getting suspended and resumed. F

Difference between Python's Generators and Iterators - Stack Overflow The 2026 Annual Developer Survey is live— take the Survey today! Collectives™ on Stack Overflow Find centralized, trusted content and collaborate around the technologies you use most. Learn more about Collectives Stack Internal Knowledge at work Bring the best of human thought and AI automation together at your work. Explore Stack Internal Difference between Python's Generators and Iterators Ask Question Asked 16 years, 2 months ago Modified 2 months ago Viewed 316k times 833 What is the difference between iterators a

Explore this link on the map →

related reading