Repeat items in list to required length

Alternative solution using some integer math instead of imports:

def repeat_items(l, c):
    return l * (c // len(l)) + l[:(c % len(l))]

>>> repeat_items([1, 2, 3], 4)
[1, 2, 3, 1]

Avoids duplicating more elements than necessary (which is particularly beneficial if len(l) is large and c is small).

Caution: does not check for empty lists


You can use itertools.cycle

Ex:

from itertools import cycle

available_items_1 = cycle([4, 2])
available_items_2 = cycle([9, 3, 12])
available_items_3 = cycle([3])

n = 4

print([next(available_items_1)for i in range(n)])
print([next(available_items_2)for i in range(n)])
print([next(available_items_3)for i in range(n)])

Output:

[4, 2, 4, 2]
[9, 3, 12, 9]
[3, 3, 3, 3]

A nice one-liner (omitting the necessity of any imports) would be:

[available_items * required_items][0][:required_items]

Testing it on your example lists we get the results you desire

required_items = 4

available_items = [4, 2]
[available_items * required_items][0][:required_items]
# Result -> [4, 2, 4, 2]

available_items = [9, 3, 12]
[available_items * required_items][0][:required_items]
# Result -> [9, 3, 12, 9]

available_items = [3, 3, 3, 3]
[available_items * required_items][0][:required_items]
# Result -> [3, 3, 3, 3]

Tags:

Python