Reputation: 7526
I am able to generate a list of random integers with replacement using a for loop, but it seems verbose and there must be a more elegant way of doing this with either pure python or using random
without a loop. Are there more optimal solutions that would produce the outcome rand_list
below without appending on every loop?
import random
rand_list = []
for x in range(100):
r = random.choice([1,2,3,4,5])
rand_list.append(r)
Upvotes: 2
Views: 2709
Reputation: 18846
You could use a comprehension
rand_list = [(random.randrange(5) + 1) for x in range(100)]
If you have a heavier function (perhaps a complex hash or return extremely large values), you can delay the creation of values by using a generator. This saves memory and allows processing to occur before the entire list has been created. You could break after a count of values, or iterate over a slice of it if only a certain number are needed (rather than a continuous process).
import itertools
import random
def gen():
while True:
yield random.randrange(5) + 1
max_iterations = 100
for value in itertools.islice(gen(), max_iterations):
do_some_opertation(value)
Upvotes: 0
Reputation: 15498
use random.choices
:
from random import choices
rand_list = choices(range(1,6),k=100)
Here k
is the number of the random numbers.
Upvotes: 1
Reputation: 18377
I believe you need to use the function choices
from the random package, you were just missing the "s"! Also, you would need to add the k
parameter to account for how many values do you want to sample:
values = [1,2,3,4,5]
print(random.choices(values,k=10))
Output:
[2, 1, 4, 2, 2, 4, 1, 2, 1, 4]
In your example, you would need to fix k to 100.
Upvotes: 7
Reputation: 46911
random.choices
does exactly what you need:
from random import choices
rand_list = choices(range(1, 6), k=100)
Upvotes: 1