Collection Recipes

Collections are data types that act as containers for zero or more other values. Python has four fundamental collection types: tuples, lists, sets, and dictionaries (often called "dicts"). Knowing their respective merits and features, knowing how to work with them, and choosing the best one for the job at hand will make your coding life faster and easier.

For a high-level overview of collection types in general, see:

This section is not really about specific "recipes". Instead, it's a quick overview of these collection types and how to do commonly-needed things to/with them.

  1. Group Related Values Into Tuples: I want to collect a few values together into a group that I can treat as one "thing", and that won’t need to change.

  2. Manage Sequences of Values with Lists: I want to build, modify, retrieve elements from, and iterate over a sequence of values.

  3. Identify Unique & Shared Elements with Sets: I want to keep track of a collection of unique values and perhaps compare the values present in different such collections.

  4. Organize Labeled Collections with Dictionaries: I want to collect related values together, with the ability to access the elements by some meaningful label rather than by a numeric index.

  5. Iterate Pythonically: I want to accomplish various iteration-related tasks while keeping my code simple and easy.