Python Glossary Русский

all Python 3itertoolsfunction

itertools.cycle

itertools

Repeat the elements of an iterable endlessly, cycling.

Syntax

itertools.cycle(iterable)

On its first pass cycle stores a copy of every element so it can repeat them forever, which means it quietly holds the whole input in memory on huge or infinite sources. The iterator itself never ends: list(cycle(...)) hangs forever, so always bound it with islice or a next() loop that has its own exit condition.

Examples

import itertools
c = itertools.cycle([1, 2, 3])
print([next(c) for _ in range(5)])   # → [1, 2, 3, 1, 2]
print(list(itertools.islice(itertools.cycle('ab'), 5)))   # → ['a', 'b', 'a', 'b', 'a']
print(list(zip('abcd', itertools.cycle([0, 1]))))   # → [('a', 0), ('b', 1), ('c', 0), ('d', 1)]
print(list(itertools.islice(itertools.cycle([]), 3)))   # → []

See also

Open in the full glossarydocs.python.orgReport an inaccuracy