On this page
random.sample
Prev: random.randrange | Up: random | Next: random.seed
Rel: random.betavariate, random.binomialvariate, random.choice, random.choices
Ref: docs.python.org — random.sample
Tags: #public #python3 #stdlib #random
Import
import random
from random import sample
Signature & Overview
random.sample(population, k, *, counts=None)
Chooses k unique random elements from a population sequence.
Usage
import random
rng = random.Random(1)
hand = rng.sample(range(1, 53), k=5)
assert len(hand) == 5 and len(set(hand)) == 5
Gotchas
- Samples WITHOUT replacement: Raises
ValueErrorifk > len(population). - Sets are no longer accepted (Python 3.11+): Convert sets with
sorted(my_set)ortuple(my_set)first.
REPL Inspect
from random import sample
help(sample)
Linked from
Related notes
- tuts/python3/stdlib_module/random/randrange Linked here; links to this page; shared tags: #random, #stdlib
- tuts/python3/stdlib_module/random/seed Linked here; links to this page; shared tags: #random, #stdlib
- tuts/python3/stdlib_module/random/betavariate Linked here; shared tags: #random, #stdlib
- tuts/python3/stdlib_module/random/binomialvariate Linked here; shared tags: #random, #stdlib
- tuts/python3/stdlib_module/random/choice Linked here; shared tags: #random, #stdlib
- tuts/python3/stdlib_module/random/choices Linked here; shared tags: #random, #stdlib
- tuts/python3/stdlib_module/random/random Linked here; shared tags: #random, #stdlib
- tuts/python3/stdlib_module/random links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/random/expovariate shared tags: #random, #stdlib
- tuts/python3/stdlib_module/random/gammavariate shared tags: #random, #stdlib