itertools count cycle and repeat Build Lazy Streams

Use itertools count, cycle, and repeat to build lazy infinite streams, then trim them with islice into finite results.

PythonData Integrity

Code

pythonsnippet
24 lines
from itertools import count, cycle, islice, repeat


def main() -> None:
    # count: 无界等差序列,用 islice 截取
    squares = [n * n for n in islice(count(1, 2), 6)]
    print('count odd squares:', squares)

    # cycle: 无限循环一个序列
    labels = list(islice(cycle(['a', 'b', 'c']), 7))
    print('cycle labels:', labels)

    # repeat: 常量重复,配合 zip 补齐
    codes = ['x1', 'x2', 'x3']
    padded = list(zip(codes, repeat('pending')))
    print('repeat pairs:', padded)

    # 三者组合:给无限流编号并截断
    stream = islice(zip(count(1), cycle(['red', 'green'])), 5)
    print('numbered stream:', list(stream))


if __name__ == '__main__':
    main()

Output

Captured from a sandboxed run of this snippet in the build pipeline.

count odd squares: [1, 9, 25, 49, 81, 121]
cycle labels: ['a', 'b', 'c', 'a', 'b', 'c', 'a']
repeat pairs: [('x1', 'pending'), ('x2', 'pending'), ('x3', 'pending')]
numbered stream: [(1, 'red'), (2, 'green'), (3, 'red'), (4, 'green'), (5, 'red')]

Inside the snippet

itertools count cycle and repeat Build Lazy Streams is built around the function main.

Putting it to use

The demo output is labeled (count odd squares:, cycle labels:, repeat pairs:), so every printed line maps back to its originating operation.

Interactive Tools for This Topic

FAQ

What does itertools count cycle and repeat Build Lazy Streams print when run?
Execute the whole file; each printed line is prefixed with a label like `count odd squares:`, `cycle labels:`, `repeat pairs:`.