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)
Using the * Operator The * operator can also be used to repeat elements of a list. When we multiply a list with any number using the * operator, it repeats the elements of the given list.
Use the multiplication operator to create a list with the same value repeated N times in Python, e.g. my_list = ['abc'] * 3 . The result of the expression will be a new list that contains the specified value N times.
To get the length of a list in Python, you can use the built-in len() function. Apart from the len() function, you can also use a for loop and the length_hint() function to get the length of a list.
Using Count() The python list method count() returns count of how many times an element occurs in list. So if we have the same element repeated in the list then the length of the list using len() will be same as the number of times the element is present in the list using the count().
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With