Batu Lab NotesPractical developer guides

Repeat a fixed schedule pattern with cycle

By Batu ยท English technical notes

Also published in our Blogger archive.

Repeat a fixed schedule pattern with cycle

By Batu.

A fixed three-stage schedule can be represented as the tuple ("warmup", "work", "cooldown"). itertools.cycle(pattern) returns an iterator that emits those values in order and then begins again at warmup. The example uses islice to take exactly eight stages, producing two complete rounds followed by the opening two stages of a third round. Its assertion verifies the exact bounded sequence before it is printed.

cycle() does not know when an application-specific schedule should end. Asking for values with next() indefinitely will continue indefinitely, so a caller needs an explicit limit, cancellation condition, or enclosing finite iterator such as islice. A repeated pattern is also not a time scheduler: it neither waits nor records timestamps. Pair the yielded stages with a separate clock or event loop when actual timing is needed.

For a finite input, cycle() saves values as it reads them so it can replay them after the original iterable is exhausted. That means cycling a large or endless source can consume growing memory; a small fixed tuple is an appropriate fit. If the tuple contains mutable objects, later repeats return references to the same objects rather than independent copies. Use immutable labels, as shown, when that shared-reference behavior is unwanted.

The Python cycle() documentation describes its repeated iterator behavior and storage note.

This technical note by Batu was drafted with AI assistance.

from itertools import cycle, islice

pattern = ("warmup", "work", "cooldown")
stages = list(islice(cycle(pattern), 8))

assert stages == [
    "warmup", "work", "cooldown", "warmup",
    "work", "cooldown", "warmup", "work",
]
assert stages.count("cooldown") == 2
print(" ".join(stages))

Expected stdout:

warmup work cooldown warmup work cooldown warmup work