I have a list of elements, N, that I want to run through repeatedly until it has M elements, where M can be any integer, not necessarily an integer multiple of N.
I found two ways to do this but neither seems as direct as I would expect is possible. Is there a more native way to do this in Python?
Here is what I came up with. Note that the first method was faster in limited testing.
from math import ceil
def repeat_list_1(values, n):
repeated = values * ceil(n / len(values))
return repeated[:n]
from itertools import cycle
def repeat_list_2(values, n):
values_cycler = cycle(values)
repeated = [next(values_cycler) for _ in range(n)]
return repeated
values = list(range(5))
n = 12
repeated1 = repeat_list_1(values, n)
repeated2 = repeat_list_2(values, n)
assert repeated1 == repeated2
print(repeated1)
[0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2]