1

I have a program below that I tried to understand the difference between an iterator and a generator.I get that a generator is an iterator and more. I appreciate the generators are short and succinct way to generate iterators. But other than brevity is there some other feature that generators provide that iterators doesn't

def squares(start, stop):
    for i in range(start, stop):
        yield i * i

generator = squares(1, 10)

print(list(generator))


class Squares(object):
    def __init__(self, start, stop):
        self.start = start
        self.stop = stop

    def __iter__(self):
        return self

    def __next__(self):
        if self.start >= self.stop:
            raise StopIteration
        current = self.start * self.start
        self.start += 1
        return current


iterator = Squares(1, 10)

l = [next(iterator) for _ in range(1,10)]
print(l)
3
  • 2
    Did you read a couple of answers already on that topic? e.g. stackoverflow.com/questions/2776829/… Commented Nov 23, 2016 at 3:00
  • Also, I found this article interesting: oreilly.com/ideas/… Commented Nov 23, 2016 at 3:01
  • @idjaw - I have taken this example from the link that you have provided. Commented Nov 23, 2016 at 3:04

1 Answer 1

3

The two examples that you've posted are equivalent.

The main advantages that generators offer over iterators (that aren't generators) is that generators use less memory, can be faster, and can be used on infinite streams.

When you use an iterator, all the items that are going to be returned eventually are calculated, then the first the element is returned.

With a generator the first element is returned before the second item is calculated.

Sign up to request clarification or add additional context in comments.

3 Comments

you mean print(list(generator)) generates one item at a time compared to the list comprehension using the iterator?
They both calculate them one at a time. The difference when they return each object. Imagine I have really big (TB) file that I want to do something to. If I have a generator that will read the the first line into memory, then yield it for me to operate on. Then it will read the second line. So even though the file might be large, or even infinite, the generator never requires more than one line to be in memory. An iterator on the other hand would read the first line into memory, then the second, etc. It would try to read the whole file into memory before it returned the first line.
thanks for the explantion. Could you perhaps point me to an example that highlights this difference between iterators and generators (i.e one that deals with a large file)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.