user17153595
user17153595

Reputation:

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.

Thank you in advance!

Upvotes: 1

Views: 64

Answers (3)

user2390182
user2390182

Reputation: 73450

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]

Upvotes: 3

Thekingis007
Thekingis007

Reputation: 647

I used 2 for loops to get the desired output

Code:

n = int(input())
ans=[]
for i in range(1,n+1):
    for j in range(i):
        ans.append(i)
print(ans)

Input:

5

Output:

[1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]

Upvotes: 0

joostblack
joostblack

Reputation: 2525

Alternative using strings:

def repetition(n):
    res = ""
    for i in range(n):
        res=res + i*str(i)
    return list(res)

Upvotes: 1

Related Questions