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

3
  • 5
    It sounds like you need random.choice. Commented Sep 29, 2015 at 20:36
  • Then make a loop and append each time? Commented Sep 29, 2015 at 20:37
  • 3
    A list comprehension would be more idiomatic than a for loop - [random.choice(seq) for _ in range(10)] or something, where seq is your list of candidate values. Commented Sep 29, 2015 at 20:38

3 Answers 3

7
vals = [random.choice(integers) for _ in range(num_ints)]
Sign up to request clarification or add additional context in comments.

Comments

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)]

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.