Python Glossary Русский

all Python 3randomterm

random.choice

selection

Returns a random item of a non-empty sequence (list, tuple, str). An empty one raises IndexError.

Syntax

random.choice(seq)

choice only handles objects that support indexing and len: a set or a generator raises TypeError, and a dict raises KeyError (or, with keys 0..n-1, silently returns a value instead of a key), so wrap them in list first (list(d) gives you a random key). Calls are independent, so the same item can come up twice in a row — when you need distinct items, use sample instead of choice in a loop.

Examples

import random
random.seed(1)
print(random.choice([1,2,3,4,5]))  # → случайный элемент
print(random.choice('abcdef'))     # → случайный символ
faces = ['♠','♥','♦','♣']
print(random.choice(faces))  # → случайная масть
import random
print([random.choice(['heads', 'tails']) for _ in range(5)])  # → ? например ['tails', 'heads', 'tails', 'tails', 'heads']
print(random.choice(range(100)))  # → ? число от 0 до 99

See also

Open in the full glossarydocs.python.orgReport an inaccuracy