On this page
itertools.cycle
Prev: itertools.count | Up: itertools | Next: itertools.dropwhile
Rel: itertools.accumulate, itertools.batched, itertools.chain, itertools.combinations
Ref: docs.python.org — itertools.cycle
Tags: #public #python3 #stdlib #itertools
Import
import itertools
from itertools import cycle
Signature & Overview
itertools.cycle(iterable, /)
Return elements from the iterable until it is exhausted. Then repeat the sequence indefinitely.
Usage
from itertools import cycle, islice
colors = cycle(["red", "green", "blue"])
assert list(islice(colors, 5)) == ["red", "green", "blue", "red", "green"]
Gotchas
- Infinite iterator: Always bound consumption with
islice(),zip(), or an explicit loop break. - Caches the entire input in memory:
cycle()saves a copy of every yielded item from the source iterable so it can repeat them—avoid wrapping huge generators.
REPL Inspect
from itertools import cycle
help(cycle)
Linked from
Related notes
- tuts/python3/stdlib_module/itertools/count Linked here; links to this page; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/dropwhile Linked here; links to this page; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/itertools/accumulate Linked here; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/batched Linked here; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/chain Linked here; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/combinations Linked here; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/combinations_with_replacement shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/compress shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/filterfalse shared tags: #itertools, #stdlib