Core data structures & comprehensions
Lists, tuples, dictionaries, sets and comprehensions.
Lists: ordered, mutable collections
The everyday workhorse collection: ordered, indexable, mutable, and allows duplicate values.
A list, written [1, 2, 3], keeps its elements in the order they were added, allows duplicates, and can be modified in place with methods like .append(), .insert(), .remove() and .pop(). Elements are accessed by zero-based index (items[0]) or sliced (items[1:3]), and negative indices count from the end (items[-1] is the last element). Lists are the right default choice for an ordered, growable collection of related items — reach for a set instead only once uniqueness and fast membership testing matter more than order.
Key points
- Lists preserve insertion order, allow duplicates, and are mutable
- .append(x) adds to the end, .insert(i, x) adds at a position, .pop() removes and returns
- Negative indices and slices (items[1:3], items[::-1]) work the same as on strings
Code
Run the code to see the result.
Building and modifying a shopping cart list with the most common list methods.
Common pitfalls
- .remove(value) removes only the first matching value and raises ValueError if none exists
- Modifying a list while iterating over it directly (for x in items: items.remove(x)) skips elements unpredictably
Practice exercise
Given a list of task names, write code that adds a new task, removes a completed one by name, and prints the tasks in reverse order using slicing.
Tuples: fixed, immutable records
Tuples look like lists but signal "this shape is fixed" and, when their elements are hashable, can be used as dict keys.
A tuple, written (1, 2, 3) (or even without parentheses in many contexts), behaves like a list for reading — indexing, slicing, iterating — but cannot be modified after creation: no .append(), no item assignment. This immutability is a feature, not a limitation: it signals to readers that a value's shape will not change, and it makes a tuple hashable (as long as its elements are), so it can be used as a dictionary key or set member, which a list never can. A single-element tuple needs a trailing comma — (5,), not (5) — because parentheses alone just group an expression.
Key points
- Tuples support reading like lists but cannot be modified after creation
- A tuple is hashable only when all of its elements are hashable, so it can then be a dict key or set member
- A one-element tuple needs a trailing comma: (5,) not (5)
Code
Run the code to see the result.
Using a tuple as a dict key, unpacking one into named variables, and the trailing-comma one-element form.
Common pitfalls
- (5) is just the integer 5 in parentheses, not a tuple — (5,) is required
- point.append(1) raises AttributeError; tuples have no mutating methods at all
Practice exercise
Write a function that takes a list of (name, score) tuples and returns the name from the tuple with the highest score, unpacking each tuple in the loop.
Dictionaries: key-value mappings
The primary tool for storing and looking up data by a meaningful name instead of a numeric position.
A dict, written {"name": "Ada", "age": 36}, maps unique, hashable keys to values, preserves insertion order (guaranteed since Python 3.7), and gives average O(1) lookup, insertion and deletion by key. Access a value with d["key"] (raises KeyError if missing) or d.get("key", default) (returns default instead of raising), iterate keys directly with for key in d:, and get key-value pairs together with .items(). Dictionaries are the natural fit whenever data is more naturally addressed by name than by position.
Key points
- d[key] raises KeyError if missing; d.get(key, default) returns default instead
- Dicts preserve insertion order and give average O(1) lookup by key
- for k, v in d.items(): iterates keys and values together
Code
Run the code to see the result.
Adding a key, safely looking up a missing one with a default, and iterating key-value pairs.
Common pitfalls
- prices["kiwi"] raises KeyError if the key is genuinely absent — use .get() or
into check safely first - Dict keys must be hashable — using a list as a key raises TypeError
Practice exercise
Write word_counts(text) that returns a dict mapping each word in text to how many times it appears, using .get(word, 0) + 1 to accumulate counts.
Sets: unique, unordered collections
Sets automatically deduplicate and offer fast membership testing plus mathematical set operations.
A set, written {1, 2, 3} or set(iterable), stores only unique, hashable elements with no guaranteed order, and offers average O(1) membership testing with in. Converting a list to a set (set(my_list)) is the standard one-line way to deduplicate values, and sets support the mathematical operators | (union), & (intersection), - (difference) and ^ (symmetric difference) directly, which read far more clearly than the equivalent loops. Because order is not preserved, sets are unsuitable whenever the original sequence order matters.
Key points
- set(list) is the standard one-line way to deduplicate values
- in on a set averages O(1), versus O(n) on a list
- | & - ^ give union, intersection, difference and symmetric difference directly
Code
Run the code to see the result.
Set operations answering "visited and wanted", "either", and "wanted but not yet visited" in one expression each.
Common pitfalls
- {} creates an empty dict, not an empty set — use set() for an empty set
- Sets do not preserve insertion order or support indexing like my_set[0]
Practice exercise
Given two lists of email addresses representing this month's and last month's subscribers, use set operations to find who unsubscribed and who is new.
List, dict and set comprehensions
A compact, idiomatic way to build a new collection by transforming and filtering an existing one.
A list comprehension [expr for item in iterable if condition] builds a new list by evaluating expr for each item that satisfies the optional if condition, replacing the equivalent four-line loop-and-append pattern with one readable line. The exact same syntax works for dicts ({k: v for k, v in pairs}) and sets ({expr for item in iterable}), and comprehensions can be nested for combinations, though nesting more than two levels usually hurts readability enough that a plain loop becomes clearer again.
Key points
- [expr for item in iterable if condition] replaces a loop-and-append pattern
- The same syntax works for dict and set comprehensions with {}
- Nesting more than two levels usually hurts readability more than it helps
Code
Run the code to see the result.
A list comprehension with a filter, a dict comprehension, and a set comprehension, side by side.
Common pitfalls
- A comprehension with side effects (like calling a function purely for its side effect) is a misuse — use a plain for loop for side effects
- Deeply nested comprehensions become harder to read than the loop they replaced
Practice exercise
Given a list of words, write one dict comprehension that maps each word to True if it has more than 4 letters and False otherwise.