Iteration

Itertools

itertools composes lazy iterator streams.

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]
ITER A1 · 2ITER B3 · 4CHAIN1 · 2 · 3 · 4
chain stitches two iterables into one stream without materialising either: values arrive lazily.

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

See also

Run the complete example

Example code

Expected output

[10, 11, 12]
['intro', 'setup', 'deploy']
[10, 10]

Execution time appears here after you run the example.