Newb
Newb

Reputation: 2930

`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

Upvotes: 1

Views: 1693

Answers (2)

UnlimitedHighground
UnlimitedHighground

Reputation: 760

In the documentation for itertools, there's a handy recipe for precisely this problem.

def consume(iterator, n):
    "Advance the iterator n-steps ahead. If n is none, consume entirely."
    # Use functions that consume iterators at C speed.
    if n is None:
        # feed the entire iterator into a zero-length deque
        collections.deque(iterator, maxlen=0)
    else:
        # advance to the empty slice starting at position n
        next(islice(iterator, n, n), None)

Upvotes: 1

Moses Koledoye
Moses Koledoye

Reputation: 78554

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

Upvotes: 2

Related Questions