Chapter 5
Collections and Iteration
Lists, tuples, dictionaries, sets, indexing, slicing, comprehensions, mutation, and copying.
What this chapter does
Real programs rarely work with one value at a time. This chapter teaches the containers Python uses for groups of values, the iteration patterns that read them, and the copying habits that keep state changes visible.
Lessons
Read these in order.
The chapter opening gives the main idea. Move through these lessons next; each page reuses ideas from the pages before it.
- 01Lists
Ordered, changeable groups of values and the basic operations they support.
- 02Tuples and Unpacking
Fixed small records, multiple return values, and assigning a structure to names.
- 03Dictionaries
Keyed lookup, counting, and storing related facts under clear names.
- 04Sets
Uniqueness, membership tests, and the small set operations used in data work.
- 05Indexing and Slicing
Selecting one item, a range of items, or a simple window from a sequence.
- 06Comprehensions
Readable one-pass transformations and filters over existing collections.
- 07Mutation and Copying
When two names share one object, when a copy is separate, and why that matters.
You are ready when
- Build and update lists.
- Unpack tuples and small records.
- Use dictionaries for keyed counts.
- Use sets for uniqueness and membership.
- Use indexing, slicing, and simple comprehensions.
- Distinguish mutation from copying.
Where this leads
- Errors and Debugging
- Files, Paths, and Modules
- NumPy Arrays