Search code examples
pythonpython-3.xgeneratorpython-itertools

`Itertools.cycle`: most pythonic way to take multiple steps?


I've got some list, and I'm looking to cycle through it. The trouble is that I'm not interested in cycling through elements one at a time, but I want to cycle through by n elements at a time.

For instance, if my list is l = ["a", "b", "c", "d"], then I would want the following output:

>>> from itertools import cycle
>>> gen = cycle(l)
>>> next(gen, 4) # I know this doesn't work -- take as pseudocode
d
>>> next(gen, 3)
c

I know that I can accomplish this with something like:

def generator_step(g, n):
    for item in range(n):
        next(g)
     return item

Solution

  • You can use itertools.islice to advance the cycle object before calling next:

    from itertools import cycle, islice
    
    c = cycle(l)
    n = 4
    print(next(islice(c, n-1, n)))
    # d