Reputation: 93
I'm indexing a dataset in python and want to generate a list repeating certain numbers up until a certain number of items in the list
There are a number of rows for my data set and i want to generate a list of [1,2,3,4,5] that repeats until it reaches the number of rows (in this case 90, but I'd like to make the code non-specific). So it would be like [1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,...] until there are 90 terms in this list. What's the most efficient way to do this? I've tried *
Upvotes: 0
Views: 64
Reputation: 7889
Use cycle
, which takes in an iterable and infinitely repeats it:
from itertools import cycle
r = cycle([1, 2, 3, 4, 5])
result = [next(r) for _ in range(90)]
print(result)
Output:
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, ...]
Upvotes: 3
Reputation: 5152
You can try this:
lst = [i % 5 + 1 for i in range(N)]
Where N
is the number of items you want (e.g. 90)
Upvotes: 0