Skip to main content

Mojo function

cycle

cycle[IterableType: Iterable](ref iterable: IterableType) -> _CycleIterator[IterableType.IteratorType[iterable_is_mut, iterable_is_origin](Copyable & Iterator)]

Creates an iterator that cycles through an iterable indefinitely.

This function returns an iterator that yields elements from the input iterable repeatedly in an infinite loop. The elements are yielded in the same order as they appear in the original iterable.

This is a lazy implementation - no work is done at construction time. The iterator keeps a copy of the original iterator and resets to it when exhausted.

Examples:

# Cycle through a list
var colors = ["red", "green", "blue"]
var color_cycle = cycle(colors)

# Get 6 elements (cycles twice)
var count = 0
for color in color_cycle:
    print(color)
    count += 1
    if count >= 6:
        break
# Output: red, green, blue, red, green, blue

Parameters:

  • IterableType (Iterable): The type of the iterable.

Args:

  • iterable (IterableType): The iterable to cycle through.

Returns:

_CycleIterator: An iterator that yields elements from the iterable forever.

Was this page helpful?