Implementation

Iterator is implemented in Python for us, within for loops, list comprehensions, and so on. Iterator in Python is simply an object that can be iterated upon. An object which will return data, one element at a time.

We can do our own implementation for special cases, using the Iterator protocol, meaning that our iterator object must implement two special methods: __iter__() and __next__().

An object is called iterable if we can get an iterator from it. Most of the built-in containers in Python (list, tuple, set, string, and so on) are iterable. The iter() function (which in turn calls the __iter__() method) returns an iterator from them.

Let's consider a football team we want to implement with the help of the FootballTeam class. ...

Get Mastering Python Design Patterns - Second Edition 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.