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)
liv2hak
  • 14,472
  • 53
  • 157
  • 270
  • 2
    Did you read a couple of answers already on that topic? e.g. http://stackoverflow.com/questions/2776829/difference-between-pythons-generators-and-iterators – idjaw Nov 23 '16 at 03:00
  • Also, I found this article interesting: https://www.oreilly.com/ideas/2-great-benefits-of-python-generators-and-how-they-changed-me-forever – elethan Nov 23 '16 at 03:01
  • @idjaw - I have taken this example from the link that you have provided. – liv2hak Nov 23 '16 at 03:04

1 Answers1

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.

Batman
  • 8,571
  • 7
  • 41
  • 80
  • you mean `print(list(generator))` generates one item at a time compared to the list comprehension using the `iterator`? – liv2hak Nov 23 '16 at 06:53
  • 1
    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. – Batman Nov 23 '16 at 12:50
  • 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) – liv2hak Nov 24 '16 at 21:32