Iterators
In typical design pattern parlance, an iterator is an object with a next()
method and a done()
method; the latter returns True
if there are no items left in the sequence. In a programming language without built-in support for iterators, the iterator would be looped over like this:
while not iterator.done(): item = iterator.next() # do something with the item
In Python, iteration is a special feature, so the method gets a special name, __next__
. This method can be accessed using the next(iterator)
built-in. Rather than a done
method, the iterator protocol raises StopIteration
to notify the loop that it has completed. Finally, we have the much more readable for item in iterator
syntax to actually access items in an iterator instead of messing ...
Get Python: Real-World Data Science now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.