[SOLVED] Do you know more efficient way to create this python list?

Issue

So, I know that is super simple, but I don’t have idea how to found the answer in google :<

It would be grate if you could tell me how I can optimalize this, or just let me know how this type of list is called.

The function takes one argument "n" and return list of numbers from 1 to "n" and every number appends "n" times

def my_function(n):
    x = []
    y = 1
    for i in range(n):
        for j in range(n):
            x.append(y)
        y += 1
    return x

my_function(3) 

Should return : [1,1,1,2,2,2,3,3,3]

Solution

Here’s one simple way with no extra libraries involved:

def my_function(n):
    # returns array from 1 to n+1 (e.g. if n=3, x=[1,2,3])
    x = list(range(1, n+1))

    # create a new array with every element of x repeated n times
    # Returns x = [1,2,3,1,2,3,1,2,3]
    x = x * n

    # Sort all elements of x to group them
    # Returns x = [1,1,1,2,2,2,3,3,3]
    x.sort()

    return x

my_function(3)

With no comments/combined, it would just be:

def my_function(n):
    x = list(range(1, n+1))* n
    x.sort()
    return x

Answered By – anonmily

Answer Checked By – Cary Denson (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *