Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use a sequence to populate a list and repeat the number by itself

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading