all Python 3randomterm
random.sample
selection
Returns a list of k distinct random items, without repetition. k cannot exceed len(population).
Syntax
random.sample(population, k)
Distinctness here is positional, not by value: if population holds equal items, the same value can appear twice in the result. A k larger than len(population) raises ValueError instead of returning a shorter list, and sets or dicts are rejected outright since 3.11 — wrap them in list() first. The population itself is left untouched, unlike random.shuffle.
Examples
import random
random.seed(7)
print(random.sample(range(10), 3)) # → 3 уникальных
print(random.sample('abcdef', 4)) # → 4 символа
deck = list(range(1,53))
hand = random.sample(deck, 5) # покерная рука
print(sorted(hand))
print(random.sample(range(1,46), 6)) # → лотерея 6 из 45
print(random.sample([1,2,3], 3)) # → перестановка
See also
Open in the full glossarydocs.python.orgReport an inaccuracy