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 get those values repeatedly.
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 on, once again, magic methods.
Iteration works in Python by its own protocol (namely the iteration protocol). When you try to iterate an object in the form for e in myobject:..., what Python checks at a very high level are the following two things, in order:
- If the object contains one of the iterator methods—__next__ or __iter__
- If the object is a sequence and has __len__ and __getitem__
Therefore, as a fallback mechanism, sequences...