Repeat items in list to required length

  • A+
Category:Languages

I have a list of available items that I can use to create a new list with a total length of 4. The length of the available item list never exceeds 4 items. If the list has less than 4 elements I want to populate it with the available elements beginning at the start element.

Example 1:

available_items = [4, 2] Result -> [4, 2, 4, 2] 

Example 2:

available_items = [9, 3, 12] Result -> [9, 3, 12, 9] 

Example 3:

available_items = [3] Result -> [3, 3, 3, 3] 

I have the feeling that my solution is not optimal, but I have found nothing better so far:

available_items = [3, 5] required_items = 4  if len(available_items) == 1:   new_items = [available_items[0]] * required_items else:   new_items = available_items + []   for i in range(required_items - len(available_items)):     new_items.append(available_items[i])  print(new_items) 

 


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] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: