Context: I’m learning python and I’d like to populate a list using range(). For example, if our n is 5, we would get [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5].
I was able to get the desired output by inserting a sublist inside a list and then replicating the numbers for each sublist by i amount of times. Then, I used nested loops to remove the sublists so that we only get one list.
def repetition(n):
sequence = []
for i in range(1,n+1):
sequence.insert(i, [i]*i)
flat_list = []
for sublist in sequence: #for every sublist inside the list sequence
for item in sublist: #get every item inside of the sublist
flat_list.append(item) #append every item to a new flat_list
return flat_list
repetition(5)
I’d like to know if there is a better way to do this with as much "vanilla" python as possible (no itertools, etc). I’ve found similar SO posts regarding this, but I haven’t found one yet that uses this example.
Thank you in advance!
>Solution :
The fix to your approach is using extend:
def repetition(n):
sequence = []
for i in range(1, n+1):
sequence.extend([i]*i)
# OR:
# for _ in range(i):
# sequence.append(i)
return sequence
But then, you can have this with a nested comprehension:
def repetition(n):
return [i for i in range(1, n+1) for _ in range(i)]
repetition(5)
# [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]