I'm looking to keep the individual elements of a list repeating for x number of times, but can only see how to repeat the full list x number of times.
For example, I want to repeat the list [3, 5, 1, 9, 8]
such that if x=12
, then I want to produce tthe following list (i.e the list continues to repeat in order until there are 12 individual elements in the list:
[3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5]
I can do the below but this is obviously not what I want and I'm unsure how to proceed from here.
my_list = [3, 5, 1, 9, 8]
x = 12
print(my_list * 12)
[3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5, 1, 9, 8]
CodePudding user response:
Your code repeats list 12 times. You need to repeat list until length is matched. This can achieved using Itertools - Functions creating iterators for efficient looping
from itertools import cycle, islice
lis = [3, 5, 1, 9, 8]
out = list(islice(cycle(lis), 12))
print(out)
Gives #
[3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5]
More pythonic #
Use a for loop to access each elemnt in list and Itterate 'lenghth' times. Repeat Ith
elemnt you access through loop in same list until length matches.
lis = [3, 5, 1, 9, 8]
length = 12
out = [lis[i%len(lis)] for i in range(length)]
print(out)
Gives ##
[3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5]
CodePudding user response:
There are multiple ways to go about it. If x
is the final length desired and lst
is the list (please do not use list
as a variable name because it overwrites the builtin list
function), then you can do :
lst = (lst * (1 x // len(lst)))[:x]
This multiplies the list by the smallest number needed to get at least N elements, and then it slice the list to keep only the first N. For your example :
>>> lst = [3, 5, 1, 9, 8]
>>> x = 12
>>> (lst * (1 x // len(lst)))[:x]
[3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5]
You could also use a loop, for example :
index = 0
while len(lst) < x:
lst.append(lst[index])
index = 1