Lists and loops

Store values, repeat processes, and reproduce generated results

Most useful programs work with more than one value. They process orders, customers, measurements, or simulated trials repeatedly and collect results in a structured form. Lists store values in order. Loops process those values or repeat a trial, while careful state design prevents skipped cases and infinite loops.

Random events make repeated trials vary. Python's random module generates values, and a seed makes the sequence reproducible. Lists and loops let you collect, check, and summarize the results. You can also sample values according to how often they occurred in observed data.

Learning objectives

By the end of this part, you will be able to:

  • create, inspect, copy, update, and traverse Python lists, including nested lists;
  • construct for and while loops with explicit state and termination;
  • use loops to count, accumulate, search, filter, and collect results;
  • diagnose off-by-one errors, unintended mutation, and non-terminating loops;
  • generate random values and use a seed to reproduce their sequence;
  • repeat a generated process, collect results, and check their count and bounds; and
  • build an empirical distribution from observed values and sample from it.