7

This question could be generalized to randomly creating a list of size n, containing pre-specified integers (assuming a uniform distribution). Hopefully it would look like the following:

Perhaps the syntax would look something like

randList([list of integers], size)

which could then produce something along the lines of:

randList([1,-1], 7)
>>> [1,-1,1,-1,-1,-1,1] #(random)

or

randList([2,3,4], 10)
>>> [4,3,4,2,2,4,2,3,4,3] #(random)

I am a bit new to python and everywhere I look it is always returning a range of values between a low and a high, and not specific values. Thanks

J. Davis
  • 113
  • 6

3 Answers3

7
vals = [random.choice(integers) for _ in range(num_ints)]
acushner
  • 9,595
  • 1
  • 34
  • 34
3

Here's a fully working example. All you need to do is replace the value of choices with the list of numbers you want to select from and replace range(10) with range(number_of_items_i_want)

import random
choices = list(range(10))
random_sample = [random.choice(choices) for _ in range(10)]

If you want this as a function so that you can reuse it, this would be an easy way to do it:

import random
def random_list(choices, size):
    return [random.choice(choices) for _ in range(size)]
Morgan Thrapp
  • 9,748
  • 3
  • 46
  • 67
1

You want to use random.choice, see this SO answer for a discussion.

However, even if you could only do values within a range:

I am a bit new to python and everywhere I look it is always returning a range of values between a low and a high

...You could still do what you want here, just assume the low/high limits to be 0 -> the size of your list, and then with each random int generated in that range, take the number at that index.

Community
  • 1
  • 1
alksdjg
  • 1,019
  • 2
  • 10
  • 26