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
Last updated 2 weeks ago