cycle

itertools.cycle allows the iterable to be gone through, repeating itself multiple times, or until the certain criteria are met. For example, if you have a plot with colors assigned by a category, and there is a chance there are more categories than colors in the style guide, you can make use of cycle. Consider the following example; we first initialize the cycle object, passing categories as arguments:

from itertools import cycle
colors = cycle(('red', 'green', 'blue'))
categories = (1, 2, 3, 4, 5)

Next, we loop over both iterators by using the zip function. As you know, generally, zip loops until the shortest collection ends. In this case, there are five categories but just three colors, so without cycling, the loop will only print the first three categories:

>>> for cat, color in zip(categories, colors):
>>> print(cat, color)

1 red
2 green
3 blue
4 red
5 green

With cycling, however, colors is essentially an infinite iterable—so the shortest one is now categories.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.81.166