Student Handbook

Student Handbook

Open in ChatGPT
Ask ChatGPT about this page
Open in Claude
Ask Claude about this page

random.choice

Picks a random item from a list or a string.

Synopsis

import random
random.choice(items)

Description

Every item has the same chance of being picked.

Parameters

Name Meaning
items A list, or a string to pick one character from.

Return value

One item.

Example

import random

colours = ["red", "green", "blue"]
print(random.choice(colours))
print(random.choice("HT"))

It prints something like this. Your values will differ: they are random.

blue
T

Common mistake

import random

print(random.choice([]))

Python stops with:

IndexError: Cannot choose from an empty sequence

An empty list has nothing to pick from.

See also

random.randint, Indexing and slicing

random.choice in the Python documentation

Last updated 2 weeks ago