← Python lessons

Python random.choice(), shuffle() and sample()

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

Python's random.choice() picks one random item from a list. random.shuffle() mixes a list up, and random.sample() picks several different items.

Read Random Numbers in Python and Lists first.

Pick one random item

random.choice(items) returns one item from the list. You don't need to work out an index with randint.

import random

moves = ["rock", "paper", "scissors"]
print(random.choice(moves))

Each run prints rock, paper or scissors. It does the same job as moves[random.randint(0, len(moves) - 1)], with less to get wrong.

Shuffle a list in place

random.shuffle(items) mixes up the list itself. It returns None, so don't print or store its result.

import random

cards = ["A", "K", "Q", "J"]
result = random.shuffle(cards)
print(cards)
print(result)

The first line shows the four cards in a random order. The second line is always None. Writing cards = random.shuffle(cards) would lose your list.

Pick several different items

random.sample(items, k) returns a new list of k different items. The original list does not change.

import random

names = ["Ada", "Sam", "Lee", "Mia"]
winners = random.sample(names, 2)
print(winners)
print(names)

winners holds two different names, in random order. names still holds all four.

choice() twice versus sample()

Calling choice() twice can pick the same item twice. Use sample() when the picks must be different, such as prize winners.

import random

names = ["Ada", "Sam"]
print(random.choice(names), random.choice(names))
print(random.sample(names, 2))

The first line is sometimes Ada Ada. The second line always holds both names.

sample() cannot pick more items than the list has.

import random

try:
    random.sample(["Ada", "Sam"], 3)
except ValueError:
    print("Not enough names to pick 3")

This prints Not enough names to pick 3.

Note: choice() on an empty list raises IndexError. These functions are fine for games, but not for passwords or security — Python's secrets module is made for that. This lesson leaves it out.

See also: Repeatable random numbers.

Your turn

Import random and pick 2 different winners from names with random.sample(). Print how many winners there are, whether the first winner is in names, and how many items names still holds.

names = ["Ada", "Sam", "Lee", "Mia"]
# import the module, pick winners with sample(), then add three prints

Expected output

2
True
4