Is there a built-in function to generate a list of random numbers of size "n"?

The standard way to create a list of random numbers is:

def generateList(n):
    randlist = []
    for i in range(n):
        randlist.append(random.randint(1,9))
    return randlist

      

However, I recently came across one random.sample

which is much more compact:

def generateList(n):
    return random.sample(range(1, 10), n)

      

But this results in an error if n

greater than 10. So my question is, is there a built-in function that does exactly what I intend to do without running into an error? If not, is there at least a more efficient alternative to the first excerpt (given that it n

can be quite large)?

+3


source to share


3 answers


The selection activity is to select as many N

items from the selection space as possible N

. This is why you are getting the error.

Having said that, there are many effective ways to solve your problem.



Note. ... Since it N

will be great if you are using Python 2.7 use xrange

instead range

. You can read more about the differences in this answer .

+4


source


No, there is no function specifically designed for this task. But you can use comprehension if you want to condense your code:



def generateList(n):
    return [randint(1, 9) for _ in range(n)]

      

+5


source


I think you will just have to try it n times, each with size 1. The reason you run into the error is that the sample does not want to repeat numbers: when you ask for 12 unique numbers from a list of 10 elements, it suffocates. Try:

def generateList(n, theList):
    return [random.sample(theList, 1) for _ in range(n)]

      

0


source







All Articles