53

What makes something iterable in Python? ie. can loop over it with for

Is it possible for me to create an iterable class in Python? If so, how?

0

4 Answers 4

67

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.

Sign up to request clarification or add additional context in comments.

2 Comments

There's also another way with __getitem__, see stackoverflow.com/a/9884259/284795
@ColonelPanic is right, if you define __getitem__ the class is also iterable. However it will ignore that you also defined __len__ and just iterate indefinitely.
9

The Python documentation describes exactly this:

One method needs to be defined for container objects to provide iteration support:

container.__iter__()

Return an iterator object. The object is required to support the iterator protocol described below. If a container supports different types of iteration, additional methods can be provided to specifically request iterators for those iteration types. (An example of an object supporting multiple forms of iteration would be a tree structure which supports both breadth-first and depth-first traversal.) This method corresponds to the tp_iter slot of the type structure for Python objects in the Python/C API.

The iterator objects themselves are required to support the following two methods, which together form the iterator protocol:

iterator.__iter__()

Return the iterator object itself. This is required to allow both containers and iterators to be used with the for and in statements. This method corresponds to the tp_iter slot of the type structure for Python objects in the Python/C API.

iterator.next()

Return the next item from the container. If there are no further items, raise the StopIteration exception. This method corresponds to the tp_iternext slot of the type structure for Python objects in the Python/C API.

Comments

5

Any object with an __iter__() method is considered an iterable.

Additionally, any sequence (objects that have an __getitem__() method) could return an iterator. An iterator is an object with a __next__() method that returns the next object in the sequence and throws a StopIteration exception.

Comments

-2

You'll want next() and __iter__() methods. Here's a nice little tutorial.

4 Comments

That tutorial is only for Python 2. For the record, Python 3 existed when this answer was posted. Here is one for Python 3.
@Asclepius saying "Python 3 already existed when this answer was posted" is a bit disingenuous - it was barely two years old, and Python 2 had plenty of life left in it .
@SiHa Thanks to your reminder, I have now flagged this answer for deletion. After all, Python 2 has no life left in it now, so the answer is not useful or applicable. To keep it is as bad as as if it were for Python 1.
@Asclepius 13 years on, I wholeheartedly agree

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.