Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

itertools.cycle

Caches items from the input and then repeats them in order.

Version: Python 3.14; repository image, production runtime not attested

Syntax

itertools.cycle(iterable, /)

Caches items from the input and then repeats them in order.

An empty input terminates immediately. A growing cache makes unbounded first-pass inputs unsuitable.

Each item from the first pass is yielded and cached. After ab is exhausted, cached a and b replay, making ababa in five pulls. Empty input ends immediately. Infinite input never finishes the first pass, so its cache can keep growing without any replay.

import itertools as I
assert list(I.islice(I.cycle([1, 2]), 5)) == [1, 2, 1, 2, 1]
assert list(I.cycle([])) == []

Examples

import itertools as I
print(list(I.islice(I.cycle("ab"), 5)))
print(list(I.cycle([])))

Result

['a', 'b', 'a', 'b', 'a']
[]

Each item from the first pass is yielded and cached. After ab is exhausted, cached a and b replay, making ababa in five pulls. Empty input ends immediately. Infinite input never finishes the first pass, so its cache can keep growing without any replay.

Sources