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.

PythonData Integrity

Code

pythonsnippet
24 lines
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

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`.