liveBook · Manning

Sampling

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

Sampling is a procedure for selecting or generating observations, values, or outcomes from a larger population, signal, or probability distribution according to a specified method.

Sampling selects one or more values from a collection. Python’s random module distinguishes choosing one item, selecting several unique items, and sampling with replacement. section 9.1.4 section 9.5

Use the function that matches the required sampling behavior:

  • Use random.choice(items) to return one item. section 9.1.4
  • Use random.sample(items, k) to return k distinct items in a new list. section 9.1.4
  • Use random.choices(items, k) when repeated selections are allowed because sampling occurs with replacement. section 9.1.4
  • Call random.seed(value) before sampling when repeated runs must produce the same pseudo-random choices. section 9.0 section 9.5

Generate an insult

Select several adjectives without repetition, select one noun, and format the result: adjs = ', '.join(random.sample(adjectives, k=3)); print(f'You {adjs} {random.choice(nouns)}!'). section 9.3.6

Mutate exact character positions

For a target number of mutations, sample character indexes with random.sample(range(len(text)), num_mutations), then replace each selected character using slices and random.choice(alpha). section 10.1.3 section 10.3.1

$ ./abuse.py
You slanderous, rotten block!
You lubbery, scurilous ratcatcher!
You rotten, foul liar!

Inspect repeated program runs to see different sampled combinations in the generated output. section 9.0

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Explains choice, unique sampling, replacement, seeding, exact index selection, and string reconstruction rather than probability theory.
Examples
Demonstrates insults, character mutation, ransom capitalization, workout selection, and word-based password generation.
What it assumes
Assumes lists, strings, loops, functions, and command-line arguments while building from concrete list-based examples.
What you can do after
Apply it via Python’s random module to select unique items, choose one value, reproduce runs, mutate text, and generate outputs.
How it connects
Connects random.sample() with random.choice(), random.choices(), random.seed(), loops, string slicing, and command-line programs.

Also explained in

Compare how 23 books explain sampling →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.