In this tutorial, you’ll learn how to solve the following programming challenge:
⚔️ Challenge: How to do random sampling from a list in Python?
Without further ado, let’s dive right into it!
Method 1: Using Function random.choice()
Description from the help function:
from random import choice seq = list(range(0,10)) print(new) for i in range(5): print(choice(seq))
This function uses the random module to pick 5 numbers from the sequence in the list. Note that the numbers can repeat. If the list is empty, it will return
It can also work for strings:
Choose a random Beethoven symphony (by opus number) to listen to. This
random.choice() command gives me one from the list “
Or from a list:
Here’s another example:
import random #Create the list of the 9 symphonies: sym = [1, 2, 3, 4, 5, 6, 7, 8, 9] print('Select Symphony No. '+str(random.choice(sym)))
Select Symphony No. 9
👉 Recommended Tutorial: Sample a Random Number from a Probability Distribution in Python
Method 2: Using Function random.choices()
If you need to choose a sample with replacement/duplicates
In the example below, we draw five cards (we set
k=5) from a 52-card deck to determine the suits. Each card draw has equal probability of being drawn.
choices(self, population, weights=None, *, cum_weights=None, k=1)
Here’s a code example:
import random #Create list of suits suits = ['Spades','Hearts','Clubs','Diamonds'] draw = random.choices(suits, k=5) print(draw)
Here we see that
Clubs are drawn three times.
What happens if there are different weights/probabilities to the outcome?
For example, in a roulette wheel, the outcomes are black, red, and green. But there are 18 spots for black and red, but only 2 for green. So, in the code we can weigh it accordingly.
import random roulette = ['Black', 'Red', 'Green'] spin = random.choices(roulette, weights=[18,18,2], k=1) print(spin)
import random import pandas as pd suits = ['Spades','Hearts','Clubs','Diamonds'] fulldeck = (list(range(1,11))+*3)*4 #print(len(fulldeck)) base_name = ['A'] + list(range(2,11)) + ['J', 'Q', 'K'] cards =  for suit in ['Spades','Hearts','Clubs','Diamonds']: cards.extend(str(num) + " of "+ suit for num in base_name) deck = pd.Series(fulldeck, index=cards) #deck def draw(deck, n=5): return deck.sample(n) draw(deck)
4 of Clubs 4 J of Clubs 10 10 of Clubs 10 9 of Spades 9 10 of Spades 10 dtype: int64
Method 3: Using Function random.sample()
Raffle Ticket Draw:
If the list itself has duplicate elements – like when picking winners in a raffle (in the example below, the number 23, then it could be returned.
import random raffle = [23, 88, 41, 23, 7, 95, 101, 33, 67, 16, 23, 41, 23] random.sample(raffle, k=5)
What about picking unique draws – like cards from a deck?
We could name the cards from 1 to 52, and run the
sample() function, to pick out 5 cards:
import random deck = list(range(1,53)) random.sample(deck, k=5)