Search code examples
pythoniteratorgenerator

Python 3: Iterator that is NOT a generator?


I'm trying to understand the difference between iterator and generator. I read that "Every generator is an iterator, but not vice versa."

Could someone give an example of an object that IS an iterator, but IS NOT a generator?

I mean, if an object has method next (which is the definition of an iterator), we can also call it a generator, can't we?

UPD: for those who say that generator must have yield - not always. (i**2 for i in range(1,5)) doesn't have yield and is also a generator.

For those who say that iter([1,2,3]) is not a generator - why? Which definition of a generator it contradicts and where?


Solution

  • "Every generator is an iterator, but not vice versa."

    I don't think that's necessarily true. The Python glossary gives 3 entries that start with "generator".

    Generator

    This is any function with a yield statement. A generator function is not an iterator, but it does return an iterator when you call it.

    def getSquares(n):
        for i in range(n):
            yield i**2
    

    Generator iterator

    This is the thing that gets returned by a generator function.

    Generator expression

    This is just a comprehension inside parentheses.

    (i**2 for i in range(10))
    

    Generator expressions and the return values of generator functions both give <class 'generator'> when you call type on them. However, if you define your own class with a __next__ method, its instances will, of course, have that class as their type.