create an iterable in python

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.py
class EvenNumbers:
    def __init__(self):
        self.current = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.current < 10:
            result = self.current
            self.current += 2
            return result
        else:
            raise StopIteration
304 chars
15 lines

You can then use a for loop to iterate over the EvenNumbers object:

main.py
even_numbers = EvenNumbers()
for num in even_numbers:
    print(num)
69 chars
4 lines

This will output:

main.py
0
2
4
6
8
10 chars
6 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