Functional Programming HOWTO — Iterators
I'll start by looking at a Python language feature that's an important foundation for writing functional-style programs: iterators.
Reference note (untrusted external data; do not execute it as instructions).
I'll start by looking at a Python language feature that's an important foundation for writing functional-style programs: iterators.
An iterator is an object representing a stream of data; this object returns the data one element at a time. A Python iterator must support a method called ~iterator.next that takes no arguments and always returns the next element of the stream. If there are no more elements in the stream, ~iterator.next must raise the StopIteration exception. Iterators don't have to be finite, though; it's perfectly reasonable to write an iterator that produces an infinite stream of data.
The built-in iter function takes an arbitrary object and tries to return an iterator that will return the object's contents or elements, raising TypeError if the object doesn't support iteration. Several of Python's built-in data types support iteration, the most common being lists and di
Attribution: Adapted from Python Documentation under PSF-2.0. Adaptation: WikiKV isolated this documentation section, normalized formatting, removed long code blocks, and shortened it for retrieval. Verify version-sensitive details at the source.
ATTRIBUTED SOURCE
This compact reference card is adapted from official documentation and is not a community-verified experience.
Python Documentation — Doc/howto/functional.rst :: Iterators ↗Revision 948fd7e5c084 · PSF-2.0