Big picture
A single variable is useful for one value, but an information task usually involves many records. A reading club may need a list of monthly loans, a fixed pair of coordinates and a lookup from book category to count. Collections express these different relationships directly.
This chapter approaches Python collections through data handling: keep identifiers distinct from positions, preserve original data when cleaning, and choose operations that match the required summary. The examples also show why copying and mutation matter when the same records are used by more than one part of a program.
Learning goals
Choose text, sequences and mappings for data tasks.
Apply collection operations without confusing return values.
Clean observations using a documented rule.
Build frequency dictionaries and calculate summaries.
Explain aliasing and verify data-integrity checks.
Core ideas
1. Choosing a collection for the task
A sequence stores items in order. Strings, lists and tuples are sequences, but they differ in mutability and purpose. A mapping associates keys with values; a dictionary is Python's usual mutable mapping. A key is not automatically a row number.
Type | Typical role | Change in place? |
|---|---|---|
str | A school or category name | No |
list | Editable observations | Yes |
tuple | Fixed grouped values | No structural reassignment |
dict | Identifier-to-record lookup | Yes |
Choose a list when positions and repeated values matter, a tuple when a fixed grouping is appropriate, and a dictionary when lookup by a unique identifier matters. A dictionary value can itself be a list or dictionary, so these structures can cooperate rather than compete. State what each key and value represents before writing operations.
2. Strings as data fields
A string stores text, including numeric-looking identifiers. Indexing selects one position and slicing selects a new string with an excluded stop. Strings are immutable. Methods such as strip, lower and replace return new text rather than changing the original.
For category matching, normalise case and trim unwanted outer whitespace in a separate cleaned field. Do not erase meaningful interior spaces in names. split separates fields into a list, while join uses a separator to combine strings. A delimiter is part of the data format: splitting on every comma is unsuitable if commas can occur inside quoted fields. At this level, state the simplifying assumption that sample fields do not contain embedded separators rather than claiming that a basic split handles every real file.
3. Lists and their essential operations
A list is an ordered mutable collection created with square brackets. It supports indexing, slicing, membership, concatenation and repetition. Negative indices count from the end. An empty list has no first item, so check before indexing.
append adds one object; extend adds the elements of an iterable; insert adds at a position. remove deletes the first matching value, while pop removes and returns an item by position. sort changes the list in place and returns None; sorted produces a separate sorted list. reverse changes order without sorting. For a data-cleaning task, distinguish removing an invalid observation from replacing it with zero: those choices affect counts and means differently. Document the cleaning rule instead of changing data merely to obtain a convenient answer.
4. A tested cleaning and summary example
The following example treats a negative number as an invalid loan count and preserves the original observations. The policy is explicit: invalid values are excluded rather than converted into real zero counts.
raw = [14, -1, 20, 16]
clean = []
for count in raw:
if count >= 0:
clean.append(count)
print(raw)
print(clean, sum(clean), len(clean))
print(round(sum(clean) / len(clean), 2))Output:
[14, -1, 20, 16]
[14, 20, 16] 50 3
16.67The valid total is 14 + 20 + 16 = 50, and the mean is 50 ÷ 3, rounded to 16.67. A real application must also handle the case where every observation is invalid, since dividing by zero would fail. Keeping raw supports later auditing.
5. Tuples, packing and unpacking
A tuple groups ordered values without permitting its own elements to be reassigned. A trailing comma distinguishes a one-element tuple from a parenthesised value. Packing groups values; unpacking binds them to corresponding names. For a pair representing city and branch, unpacking makes each role readable.
Tuples support many non-mutating sequence operations, including indexing, slicing, count and index. They do not support append. A tuple containing a list can still expose changes to that list, because immutability applies to the tuple's own structure. A tuple used as a dictionary key must contain only hashable components. Do not assume “tuple” alone proves a key is valid if a nested element is an unhashable list.
6. Dictionaries for lookup and frequency
A dictionary stores unique hashable keys with associated values. New assignment replaces the value if the key already exists. Values can repeat. get supplies a missing-key fallback without inserting it; brackets raise KeyError when a key is absent.
categories = ["science", "arts", "science", "sports"]
frequency = {}
for name in categories:
frequency[name] = frequency.get(name, 0) + 1
print(frequency)
print(frequency.get("music", 0))Output:
{'science': 2, 'arts': 1, 'sports': 1}
0Each observation increases exactly one count. The frequency total is four, matching the input length. This invariant is a useful independent check. Normalise labels before counting only if the task treats differently cased labels as the same category.
7. Aliasing, shallow copies and nested records
Assignment makes another name refer to the same object; it does not copy the object's contents into an independent structure. A slice or copy method creates a shallow outer copy, but nested mutable objects remain shared. Draw references when records contain lists.
original = [5, 9]
alias = original
separate = original[:]
alias.append(12)
print(original, separate)Output:
[5, 9, 12] [5, 9]The separate outer list was made before the append. For nested records, do not assume the same outer-copy technique isolates every field. Prefer constructing the required independent data deliberately and test a nested mutation if independence matters. A function that cleans a list in place should document that side effect so later analysis does not unknowingly use changed raw data.
8. Traversal, aggregation and integrity checks
Traverse a list directly when only values matter, and use indices when positions are required. Dictionary items provides key–value pairs. Avoid changing a dictionary's size while traversing it; plan changes separately. Removing list items during forward traversal can shift later positions and cause skips.
Aggregation summarises observations with a count, total, minimum, maximum or average. Check nonempty input before operations that need an item or denominator. For a largest-value algorithm, initialise from a real first value rather than zero, because all valid values might be negative. Check that category frequencies add to the number of included records and that excluded records are documented. A correct summary is reproducible from a stated dataset and cleaning rule, not merely a number printed by a program.
A reliable approach to questions
Read the command word before choosing an answer. A definition needs the distinguishing feature; a comparison needs matching criteria on both sides; an application needs a reason linked to the situation.
Extract the supplied evidence and assumptions. Keep a small working table rather than relying on memory. If information is absent, state the limit instead of inventing a value or claiming certainty.
Work through the relevant rule one step at a time. For a program, record the changing state; for a scenario, connect the requirement to the feature that meets it. Explain why the closest alternative fails.
Check the result against the original question, including boundary cases, units and wording. Present a concise final answer followed by enough reasoning for another student to reproduce your conclusion.
Connections that matter
Programming basics provide loops and comparisons for cleaning.
Database concepts extend keyed records into relational tables.
Data projects require preserved raw data and reproducible summaries.
Common mistakes
Replacing missing data with zero silently: zero is a real observation.
Assuming list assignment copies: aliases share one object.
Expecting get to insert defaults: it retrieves without insertion.
Dividing by an unchecked count: empty valid data need a separate policy.
Revision checklist
I can choose text, sequences and mappings for data tasks.
I can apply collection operations without confusing return values.
I can clean observations using a documented rule.
I can build frequency dictionaries and calculate summaries.
I can explain aliasing and verify data-integrity checks.