ryentzer
ryentzer

Reputation: 166

How to create a small random list from a larger list with Python

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

Upvotes: 0

Views: 617

Answers (2)

Nick Reed
Nick Reed

Reputation: 5059

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

small_list = random.sample(words, 4)

Demo

Upvotes: 1

Thierry Lathuille
Thierry Lathuille

Reputation: 24232

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

Upvotes: 4

Related Questions