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)?
source to share
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.
-
We can just wrap your code in a list comprehension like
def generateList(n): return [randint(1, 9) for i in range(n)]
-
Use
randrange
insteadrandint
, like thisdef generateList(n): return [randrange(1, 10) for i in range(n)]
-
If the number of possible items is small, you can even use
choice
like thisdef generateList(n, sample_space = range(1, 10)): return [choice(sample_space) for i in range(n)]
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 .
source to share
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)]
source to share