Python 3 crumbs tagged with #iterators

Create an iterable with a constructor

Create an iterable with a constructor

May 24, 2022 by erik

Add a constructor to the EvenNumbers class that accepts a parameter called max. This max comes instead of the hard-coded value of 8. So the iterator must return values until it reaches this max value, but it must include the...

iterators
Demonstration of how a Python range works

Demonstration of how a Python range works

Mar 6, 2022 by erik

A range is an iterable object, and this object can return an iterator that keeps track of its current state. Suppose we create a range with the call range(3). This returns an object of type range with our requested settings....

range iterators
Creating a Python iterator

Creating a Python iterator

Mar 1, 2022 by erik

There’s no magic to creating your own iterator. I’ll demonstrate with a simple iterator class that returns even numbers. As we’ve learned, we need to implement __iter__ and __next__. We’ll do this in one single class, to keep things simple....

iterators classes