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

2 Answers 2

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']
Sign up to request clarification or add additional context in comments.

1 Comment

Great! Exactly the python zen I was looking for.
1

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

small_list = random.sample(words, 4)

Demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.