2

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)
iskandarblue
  • 7,208
  • 15
  • 60
  • 130

5 Answers5

6

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.

Celius Stingher
  • 17,835
  • 6
  • 23
  • 53
1

random.choices does exactly what you need:

from random import choices

rand_list = choices(range(1, 6), k=100)
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
1

use random.choices:

from random import choices

rand_list = choices(range(1,6),k=100)

Here k is the number of the random numbers.

Wasif
  • 14,755
  • 3
  • 14
  • 34
0

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)
ti7
  • 16,375
  • 6
  • 40
  • 68
0
print(list(random.choices([1, 2, 3, 4, 5], k=100)))
Dejene T.
  • 973
  • 8
  • 14