Iterable Objects

Learn how to create iterable objects and sequences.

In Python, we have objects that can be iterated by default. For example, lists, tuples, sets, and dictionaries can not only hold data in the structure we want, but also be iterated over a for loop to process the data. However, the built-in iterable objects are not the only kind that we can have in a for loop. We could also create our own iterable, with the logic we define for iteration.

In order to achieve this, we rely, once again, on magic methods.

Iteration works in Python by its own protocol (namely the iterator protocol). When we try to iterate an object in the form for e in myobject:..., what Python checks at a very high level are these two things, in order:

  • Whether the object contains one of the iterator methods—__next__ or __iter__.

  • Whether the object is a sequence and has __len__ and __getitem__.

Therefore, as a fallback mechanism, sequences can be iterated, and so there are two ways of customizing our objects to be able to work on for loops.

Creating iterable objects

When we try to iterate an object, Python will call the iter() function over it. One of the first things this function checks for is the presence of the __iter__ method on that object, which, if present, will be executed.

The code below creates an object that allows iterating over a range of dates, producing one day at a time on every round of the loop:

Get hands-on with 1400+ tech skills courses.