Why is an iterable object not an iterator?

The concept of iteration is well documented in the Python documentation.

In short, “iterable” is the object which provides the items I want to iterate over. Either it already cintains these items, then it is also called the container. This can be a list, a string, a tuple or anything else which consists of zero to many items.
But it also can be an object which produces items, for example one of the many classes contained in itertools. It has __iter__() which returns an iterator.

An “iterator” is the object which is used for one iteration. It can be seen as a kind of “cursor”. It has next() (in Python 2) or __next__() (in Python 3) which is called repeatedly until it raises a StopIteration exception. As any iterator is iterable as well (being its own iterator), it also has __iter__() which returns itself.

You can get an iterator for any iterable with iter(obj).

In your example, linehistory (which should be written LineHistory) is iterable as it has an .__iter__(). The generator object created with this is an iterator (as every generator object).

Leave a Comment

404 Not Found

Not Found

The requested URL was not found on this server.

Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.