Python Iterators: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 13: Line 13:
l = ['a', 'b', 'c']
l = ['a', 'b', 'c']
i = iter(l)
i = iter(l)
</syntaxhighlight>
Once created, repeated invocations of the iterator's <code>__next__()</code> method, or by passing it to the built-in function <code>[[Python Language Functions#next|next()]]</code>, return successive items in the stream:
<syntaxhighlight lang='py'>
assert next(i) == 'a'
assert next(i) == 'b'
assert next(i) == 'c'
</syntaxhighlight>
</syntaxhighlight>

Revision as of 04:58, 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'