Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python itertools.cycle() Function



The Pythonitertools.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 −

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

Following is the output of the above code −

redgreenblueredgreenblue

Example 2

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

import itertoolstuple_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 −

1231231

Example 3

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

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

The result obtained is as shown below −

ABABAB

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 theislice() function from itertools.

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

import itertoolsletters = ["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 −

XYZXYZXY
python_modules.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp