An iterable is any object that can return an iterator, which can traverse the object’s data. Creating an iterable in Python is quite simple. All you need to do is define an object with the __iter__()
method. This method should return an object with a __next__()
method, which is used to iterate over the object.
Here is an example of creating an iterable that returns the first 5 even numbers (starting at 0):
main.py304 chars15 lines
You can then use a for loop to iterate over the EvenNumbers object:
main.py69 chars4 lines
This will output:
main.py10 chars6 lines
Note that we define the __init__()
method to set the initial state of the object, and the __next__()
method to return the next item in the sequence. The __iter__()
method simply returns the object itself, as it is already an iterator.
gistlibby LogSnag