What makes something iterable in python

To make a class iterable, write an __iter__() method that returns an iterator:

class MyList(object):
    def __init__(self):
        self.list = [42, 3.1415, "Hello World!"]
    def __iter__(self):
        return iter(self.list)

m = MyList()
for x in m:
    print(x)

prints

42
3.1415
Hello World!

The example uses a list iterator, but you could also write your own iterator by either making __iter__() a generator or by returning an instance of an iterator class that defines a __next__() method.

Leave a Comment