Pylander Pylander - 2 months ago 7
Python Question

Python Repeat List to Max Number of Elements

What is the most efficient method to repeat a list up to a max element length?

To take this:

list = ['one', 'two', 'three']
max_length = 7


And produce this:

final_list = ['one', 'two', 'three', 'one', 'two', 'three', 'one']

Answer

I'd probably use iterools.cycle and itertools.islice:

>>> from itertools import cycle, islice
>>> lst = [1, 2, 3]
>>> list(islice(cycle(lst), 7))
[1, 2, 3, 1, 2, 3, 1]