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

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',....]



Solution 1:[1]

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', . . .]

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2