Python Iterators: Difference between revisions
Jump to navigation
Jump to search
Line 21: | Line 21: | ||
assert next(i) == 'c' | assert next(i) == 'c' | ||
</syntaxhighlight> | </syntaxhighlight> | ||
When no more data are available a <code>StopIteration</code> exception is raised instead. At this point, the iterator object is exhausted and any further calls to its <code>__next__()</code> method just raise <code>StopIteration</code> again. |
Revision as of 05:01, 7 July 2022
External
Internal
TODO
TO PROCESS PyOOP "The Iterator Pattern" + "Iterators" + "The iterator protocol"
Overview
An iterator instance represents a stream of data.
The iterator instances are created from iterable objects with the built-in function iter()
:
l = ['a', 'b', 'c']
i = iter(l)
Once created, repeated invocations of the iterator's __next__()
method, or by passing it to the built-in function next()
, return successive items in the stream:
assert next(i) == 'a'
assert next(i) == 'b'
assert next(i) == 'c'
When no more data are available a StopIteration
exception is raised instead. At this point, the iterator object is exhausted and any further calls to its __next__()
method just raise StopIteration
again.