2121
Comment:
|
2130
Update to Py3 syntax
|
Deletions are marked like this. | Additions are marked like this. |
Line 20: | Line 20: |
def next(self): | def __next__(self): |
Line 37: | Line 37: |
print eggs | print(eggs) |
Line 56: | Line 56: |
An object isn't iterable unless it provides {{{__iter__}}}. And for an object to be a valid iterator, it must provide {{{next}}}. | An object isn't iterable unless it provides {{{__iter__}}}. And for an object to be a valid iterator, it must provide {{{__next__}}}. |
An iterable object is an object that implements __iter__, which is expected to return an iterator object.
An iterator is an object that implements next, which 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.
Example Iterator
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__.
Links
See also: Generators
Discussion
- (none yet!)