Iteration
Itertools
count() can produce values forever, so islice() takes a finite window. Nothing is materialized until list() consumes the iterator.
Source
import itertools
counter = itertools.count(10)
print(list(itertools.islice(counter, 3)))Output
[10, 11, 12]chain() presents several iterables as one stream. This avoids building an intermediate list just to loop over combined inputs.
Source
pages = itertools.chain(["intro", "setup"], ["deploy"])
print(list(pages))Output
['intro', 'setup', 'deploy']Iterator helpers compose with ordinary Python expressions. compress() keeps items whose corresponding selector is true.
Source
scores = [7, 10, 8, 10]
high_scores = itertools.compress(scores, [score >= 9 for score in scores])
print(list(high_scores))Output
[10, 10]Notes
itertoolscomposes producer and transformer streams.- Iterator pipelines avoid building intermediate lists.
- Use
islice()to take a finite piece from an infinite iterator. - Convert to a list only when you need concrete results.
See also
- related: Iterators
- related: Generator Expressions
- related: Sentinel Iteration
- prerequisite: Comprehension Patterns
Run the complete example
Expected output
[10, 11, 12]
['intro', 'setup', 'deploy']
[10, 10]
Execution time appears here after you run the example.