Member-only story
Easy Python Patterns: The Iterator — Code nomad
Introduction
In Design Patterns, the Iterator is a way of traversing over a container, that is access each of the container’s elements. It is used as a convenient way to traverse over lists or arrays, but it could also be used to traverse over binary trees for example.
It looks like this:
A bit of explanation can be handy:
- An iterator basically has two methods: next() and hasNext()
- The next() method returns the next element in the container
- The hasNext() method returns a bool, true if a next element is available, false if there is no next element.
Implementation in Python
Like many modern languages, iterators are built into the language itself, lists and tuples for example can be iterated over. For our purpose we will build our own custom iterator, which just yields even numbers, up to a certain limit. You will see it will behave just like any other iterable type.
Since we want to return the type of the enclosing class, we need the following import:










