Search code examples
pythonpython-itertoolscycle

itertools: cycle through several lists N times via iteration


I would like to replace:

colors=itertools.cycle(('k','k','k','k','k','k','k','k','k','k','k','k','b','b','b','b','b','b','b','b','b','b','b','b','b','b','g','g','g','g','g','g','g','g','g','g','g','g','g'))

with a more elegant formulation. I tried:

colors = itertools.chain.from_iterable(itertools.repeat(['k'], 12), itertools.repeat(['b'], 14), itertools.repeat(['g'], 13))

but it does not work, how can I do it?

Thanks a lot for your help


Solution

  • Simple way:

    from itertools import cycle
    
    colors = cycle('k'*12 + 'b'*14 + 'g'*13)
    

    (If your strings aren't just single characters, wrap them in lists like ['k']*12.)

    With more itertools:

    from itertools import cycle, repeat, chain, starmap
    
    spec = ('k', 12), ('b', 14), ('g', 13)
    colors = chain.from_iterable(starmap(repeat, cycle(spec)))
    
    from itertools import cycle, repeat, chain, starmap
    
    spec = ('k', 12), ('b', 14), ('g', 13)
    colors = cycle(chain(*starmap(repeat, spec)))
    

    Test at Attempt This Online!