Python itertools.cycle() Function



The Python itertools.cycle() function is used to create an iterator that repeats the elements of an iterable indefinitely in the same order. This function is commonly used for cycling through elements in a sequence repeatedly.

It loops over the given iterable infinitely unless manually stopped.

Syntax

Following is the syntax of the Python itertools.cycle() function −

itertools.cycle(iterable)

Parameters

This function accepts the iterable as a parameter whose elements will be cycled through repeatedly.

Return Value

This function returns an iterator that cycles through the elements of the given iterable indefinitely.

Example 1

Following is an example of the Python itertools.cycle() function. Here, we cycle through a list of strings −

Open Compiler
import itertools colors = ["red", "green", "blue"] color_cycle = itertools.cycle(colors) for _ in range(6): print(next(color_cycle))

Following is the output of the above code −

red
green
blue
red
green
blue

Example 2

Here, we cycle through the elements of a tuple repeatedly using the itertools.cycle() function −

Open Compiler
import itertools tuple_values = (1, 2, 3) number_cycle = itertools.cycle(tuple_values) for _ in range(7): print(next(number_cycle))

Output of the above code is as follows −

1
2
3
1
2
3
1

Example 3

Now, we use the itertools.cycle() function with a string to cycle through its characters −

Open Compiler
import itertools text = "AB" char_cycle = itertools.cycle(text) for _ in range(6): print(next(char_cycle))

The result obtained is as shown below −

A
B
A
B
A
B

Example 4

If you use the itertools.cycle() function without limiting its iteration, it will run indefinitely. To prevent infinite loops, you can use conditions or the islice() function from itertools.

Here, we cycle through a list but limit it using itertools.islice() function −

Open Compiler
import itertools letters = ["X", "Y", "Z"] letter_cycle = itertools.cycle(letters) limited_cycle = itertools.islice(letter_cycle, 8) for letter in limited_cycle: print(letter)

The result produced is as follows −

X
Y
Z
X
Y
Z
X
Y
python_modules.htm
Advertisements