liveBook · Manning

Random module

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

random is Python's standard-library module for generating pseudo-random values and performing random selections.

The random module generates pseudo-random values and makes selections from collections. Its results depend on an internal state, so a seed can make behavior reproducible for tests and demonstrations. section 9.1.2 section 9.3.4

Common operations include:

  • Call random.choice() to select one item from a list and random.sample() to select several items. section 9.5
  • Call random.seed(value) with a hashable value, commonly an integer, to reproduce a sequence of pseudo-random decisions. section 9.3.4
  • Call random.shuffle(list) to reorder a mutable list in place; the method returns None. section 16.1.4

Reproducible random output

A command-line program can pass an integer seed to random.seed(args.seed), then select words to generate predictable output during tests. Without a supplied seed, random.seed(None) behaves like leaving the generator unseeded. section 9.1.2 section 12.0

Scrambling mutable data

To scramble the middle of a word, convert the string slice to a list, shuffle that list, and join it with the unchanged first and last characters. Strings cannot be shuffled in place. section 16.1.4

random.seed(args.seed)

Inspect the minimal seeding call used to control pseudo-random behavior. section 9.3.4

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

How deep it goes
Explains pseudo-random state, hashable seeds, selection functions, and in-place shuffling, but does not develop generator internals.
Examples
Demonstrates random insults, ransom-note capitalization, workout selection, and shuffled word middles.
What it assumes
Assumes familiarity with lists, strings, functions, command-line arguments, and tests, while demonstrating mutability through a concrete shuffle example.
What you can do after
Apply it via Python functions to select items, transform text, shuffle lists, and reproduce results with controlled seeds.
How it connects
Connects random choices with lists, strings, command-line arguments, testing, and mutable versus immutable values.

Also explained in

Compare how 4 books explain random module →

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.