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


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):
        y += 1
    return x


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


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]

    return x


With no comments/combined, it would just be:

def my_function(n):
    x = list(range(1, n+1))* n
    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 *