Random Sample And Weighted Choices
With a seeded Random, sample draws without replacement and rejects oversized k, choices draws with replacement under weights, shuffle reorders in place.
Code
import random
rng = random.Random(7)
deck = ['react', 'vue', 'svelte', 'solid', 'qwik']
# sample draws k items WITHOUT replacement: no item repeats
drawn = rng.sample(deck, k=3)
print('sample k=3 :', drawn)
print('sample k=2 :', rng.sample(drawn, k=2))
# k larger than the population raises ValueError
try:
rng.sample(deck, k=6)
except ValueError as error:
print('sample k=6 :', type(error).__name__)
# choices draws WITH replacement and accepts weights to bias the draw
weights = [50, 25, 15, 7, 3]
picks = rng.choices(deck, weights=weights, k=10)
print('react picks:', picks.count('react'), 'of 10')
# shuffle reorders in place; sample(deck, k=len(deck)) would copy instead
rng.shuffle(deck)
print('shuffled :', deck)Output
Captured from a sandboxed run of this snippet in the build pipeline.
sample k=3 : ['svelte', 'vue', 'solid']
sample k=2 : ['solid', 'svelte']
sample k=6 : ValueError
react picks: 8 of 10
shuffled : ['vue', 'svelte', 'solid', 'react', 'qwik']How the snippet works
The file’s state is a handful of top-level bindings: rng, deck, drawn, weights.
What to watch for
- No install step: all APIs used ship with the platform.
Using it
Expect labeled output — sample k=3 :, sample k=2 :, sample k=6 : — when the file runs.
Key statements
except ValueError as error:
print('sample k=6 :', type(error).__name__)
Interactive Tools for This Topic
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.Passphrase GeneratorGenerate memorable multi-word passphrases from a fixed 150-word list with crypto randomness, separators, and capitalization options.Password GeneratorGenerate random passwords from selectable character classes using crypto.getRandomValues with rejection sampling and class guarantees.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What has to be installed first?
- Nothing — the runtime itself provides everything the code touches. Every import resolves inside the standard library — `random`. Its state lives in module-level bindings: `rng`, `deck`, `drawn`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.