3

The standard way of creating 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 stumbled upon 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 is greater than 10. So, my question is, does there exist a built-in function that does exactly what I intend it to do without running into error? If not, is there at least a more efficient alternative to the first excerpt (considering that n can be quite large)?

buydadip
  • 8,890
  • 22
  • 79
  • 154
  • 3
    You are misinterpreting `random.sample`: notice that none of the numbers in the random list ever appears twice. A shorter version of `generateList` is `lambda n: [randint(1,9) for _ in range(n)]`. – Alec Jan 12 '15 at 22:57

3 Answers3

5

No, there is not a function specifically dedicated to this task. But you can use a list comprehension if you want to condense the code:

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

The activity of sampling is to select a maximum of N elements from the sample space of size N. That is why you are getting an error.

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

  1. We can simply wrap your code in a list comprehension, like this

    def generateList(n):
        return [randint(1, 9) for i in range(n)]
    
  2. Use randrange instead of randint, like this

    def generateList(n):
        return [randrange(1, 10) for i in range(n)]
    
  3. If the number of possible elements is small, you can even use choice like this

    def generateList(n, sample_space = range(1, 10)):
        return [choice(sample_space) for i in range(n)]
    

Note: Since n is going to large, if you are using Python 2.7, use xrange instead of range. You can read more about the differences in this answer.

Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
0

I think you're going to just have to sample it n times, each with size 1. The reason you are running into the error is that sample doesn't want to repeat numbers: when you ask for 12 unique numbers from a 10 element list, it chokes. Try:

def generateList(n, theList):
    return [random.sample(theList, 1) for _ in range(n)]
Henry Crutcher
  • 2,137
  • 20
  • 28