O'Reilly logo

Practical Time Series Analysis by Dr. PKS Prakash, Dr. Avishek Pal

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required