python repeat list elements in an iterator
Question: Is there any way to create an iterator to repeat elements in a list certain
times? For example, a list is given:

    
    
    color = ['r', 'g', 'b']
    

Is there a way to create a iterator in form of `itertools.repeatlist(color,
7)` that can produce the following list?

    
    
    color_list = ['r', 'g', 'b', 'r', 'g', 'b', 'r']
    


Answer: You can use
[`itertools.cycle()`](https://docs.python.org/2/library/itertools.html#itertools.cycle)
together with
[`itertools.islice()`](https://docs.python.org/2/library/itertools.html#itertools.islice)
to build your `repeatlist()` function:

    
    
    from itertools import cycle, islice
    
    def repeatlist(it, count):
        return islice(cycle(it), count)
    

This returns a new iterator; call `list()` on it if you must have a list
object.

Demo:

    
    
    >>> from itertools import cycle, islice
    >>> def repeatlist(it, count):
    ...     return islice(cycle(it), count)
    ...
    >>> color = ['r', 'g', 'b']
    >>> list(repeatlist(color, 7))
    ['r', 'g', 'b', 'r', 'g', 'b', 'r']
    

