How to add random words up to n times in a list?

Viewed 45

I want a numpy array of size n, with words from the list words = ["high","low","neutral"] filled up to size n randomly.

I tried x = [random.sample(words,1) for i in range(1,101)].

This gave the output like this: [['low'],['high']...]

I want the output as: ['high','low','low',....]

2 Answers

You should use random.choices():

x = random.choices(words, k=100)

The docs for random.choices() state:

Return a k sized list of elements chosen from the population with replacement. If the population is empty, raises IndexError.

Basically you are doing it right, but random.sample returns the list of random selections so in your case you can do either replace the

x = [random.sample(words,1) for i in range(1,101)]

with

x = [random.sample(words,1)[0] for i in range(1,101)]

Output ['high', 'low', 'low', . . .]

Or also you can use list comprehension to tackle this, e.g.

x = [x[0] for x in x]

Output ['high', 'low', 'low', . . .]

Or you can simply make it super simple one liner by using random.choices

x = random.choices(words, k=100)

Output ['high', 'low', 'low', . . .]

Related