Iterators

Objects that are instances of classes that have __iter__ and next functions and can be used with a for loop to go over a sequence element by element are iterators. The __iter__ function makes an object recognizable as an iterator. The next function is invoked to get the elements of a sequence one by one. Every time the next function is called, it returns an element from the predefined sequence or it creates an element. Hence, the next function can implement the logic to create the elements. When there are no more elements, the __next__ function throws a StopIteration error.

Let's go through examples to understand how iterators work. We create an iterator to return elements from a predefined sequence:

class MyIterator(object):def ...

Get Practical Time-Series Analysis 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.