0

I want to create a list containing three items randomly chosen from a list of many items. This is how I have done it, but I feel like there is probably a more efficient (zen) way to do it with python.

import random

words = ['bacon', 'gorilla', 'phone', 'hamburger', 'mother']

small_list = []

while len(small_list) < 4:
    word = random.choice(words)
    if word not in small_list:
        small_list.append(word)

Expected output would be something like:

small_list = ['phone', 'bacon', 'mother']
ryentzer
  • 169
  • 2
  • 10

2 Answers2

4

Use random.sample:

Return a k length list of unique elements chosen from the population sequence or set. Used for random sampling without replacement.

import random

words = ['bacon', 'gorilla', 'phone', 'hamburger', 'mother']
small_list = random.sample(words, k=3)

print(small_list)
# ['mother', 'bacon', 'phone']
Thierry Lathuille
  • 22,718
  • 10
  • 38
  • 45
1

From this answer, you can use random.sample() to pick a set amount of data.

small_list = random.sample(words, 4)

Demo

Nick Reed
  • 5,007
  • 4
  • 15
  • 36