An iterable object is an object that implements __iter__. __iter__ is expected to return an iterator object.
An iterator is an object that implements next. next is expected to return the next element of the iterable object that returned it, and raise a StopIteration exception when no more elements are available.
In the simplest case the iterable will implement next itself and return self in __iter__.
You can use iterables in for loops, and you can use them to construct lists.
Here is an iterator that returns a random number of 1's:
Q: Why is __iter__ there, if it just returns self?
A: This is a very simple case. More complex iterables may very well return separate iterator objects.
Q: When would I need an extra iterator?
A: Iterator will typically need to maintain some kind of position state information (like the index of the last element returned or the like). If the iterable maintained that state itself, it would become inherently non-reentrant (meaning you could use it only one loop at a time).
You can also use it in list construction:
...both of these uses require __iter__.
An object isn't iterable unless it provides __iter__. And for an object to be a valid iterator, it must provide next.
See also: Generators
- (none yet!)