Home > Software engineering >  Do you know more efficient way to create this python list?
Do you know more efficient way to create this python list?

Time:03-04

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]

CodePudding user response:

You mean smaller like this?

def foo(n):
    result = []
    for i in range(1, n   1):
        result  = ([i]*n)
    return result

foo(3)

CodePudding user response:

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

CodePudding user response:

One liner pythonic way:

def foo(n):
    return [i for i in range(1, n 1) for _ in range(n)]

foo(3)
  • Related