Skip to content

04. Data structures

Until now, each value had its own variable: r1, r2, r3. Real data has hundreds or millions of values. This module gives you the four containers that hold them: lists of sensor readings, tuples as fixed records, dicts of customer records and sets of product ids. You also learn how Python stores these containers in memory, because that explains the most common data bugs: a “copy” that changes the original.

  • Store and change ordered data in a list, and fixed records in a tuple.
  • Look up values by key in a dict, and keep unique values in a set with fast membership tests and set algebra.
  • Read nested structures such as the customer records in data/customers.json, and unpack values into names, with * for “the rest”.
  • Explain mutability and aliasing, and choose between a shallow copy and a deep copy.
  • Write list, dict and set comprehensions to filter and reshape data.
  • Choose the right structure for a task, with a big-O intuition for how fast a membership test is.

A data structure is a way to organize many values so that you can store, find and change them. Python has four built-in ones. Each is a container: an object that holds other objects. The values inside a container are its elements (or items).

Structure Literal Ordered Changeable Duplicates Typical data
list [21.0, 21.9, 21.4] yes yes yes readings in time order, rows of a table
tuple ("S1", 21.0) yes no yes one fixed record: id and value, a coordinate
dict {"plan": "basic"} by insertion yes keys unique a customer record, a lookup table by id
set {"P001", "P014"} no yes no unique product ids, tags, “seen” ids

“Ordered” means that the container keeps the elements in a fixed position. You can ask for the first one. “Changeable” means that you can add, remove or replace elements after you create the container.

Every structure answers one question fast. A list answers “what is at position 3?”. A dict answers “what is the value for key C00017?”. A set answers “is P014 in here?”. The rest of this page shows each one, then how to choose.

A list is an ordered sequence of values in square brackets. Use it for data whose order matters, such as sensor readings in time order. A list can hold any type, and the types can mix, but a list of one type is easier to work with.

readings = [21.0, 21.9, 21.4, 21.7, 22.1, 22.0]
print(readings)
print(len(readings), readings[0], readings[-1])
print(readings[1:4], readings[-2:])
Output
[21.0, 21.9, 21.4, 21.7, 22.1, 22.0]
6 21.0 22.0
[21.9, 21.4, 21.7] [22.1, 22.0]

Lists use the indexing and slicing of strings (module 02). The first index is 0 and -1 is the last element. A slice readings[1:4] is a new list with the elements at positions 1, 2 and 3. The stop index is not included.

The built-in functions len(), sum(), min() and max() accept a whole list. The mean (average) of nn values is their sum divided by nn:

xˉ=1n∑i=1nxi\bar{x} = \frac{1}{n} \sum_{i=1}^{n} x_i
mean = sum(readings) / len(readings)
print(f"n={len(readings)} min={min(readings)} max={max(readings)} mean={mean:.2f}")
Output
n=6 min=21.0 max=22.1 mean=21.68

Unlike a string, a list can change in place. A method is a function that belongs to an object; you call it with a dot, as in readings.append(22.5). These methods change the list itself and return None:

Method Does Example
append(x) adds x at the end readings.append(22.5)
extend(items) adds every element of items at the end readings.extend([22.9, 22.2])
insert(i, x) puts x at position i readings.insert(0, 20.8)
pop() / pop(i) removes and returns the last element / the element at i last = readings.pop()
remove(x) removes the first element equal to x readings.remove(21.4)
sort() sorts the list in place readings.sort(reverse=True)
reverse() reverses the order in place readings.reverse()
clear() removes every element readings.clear()
readings.append(22.5)
readings.extend([22.9, 22.2])
readings[0] = 20.9 # replace the element at index 0
removed = readings.pop()
print(readings)
print("popped:", removed)
print(21.4 in readings, readings.count(22.9), readings.index(22.1))
Output
[20.9, 21.9, 21.4, 21.7, 22.1, 22.0, 22.5, 22.9]
popped: 22.2
True 1 4

The operator in tests membership: is this value an element of the list? count(x) counts the elements equal to x, and index(x) gives the position of the first one.

Two operators build new lists. + joins two lists end to end, and * repeats a list:

print([21.0, 21.9] + [22.1], [0] * 3)
Output
[21.0, 21.9, 22.1] [0, 0, 0]

sorted(readings) returns a new sorted list and leaves the original alone. readings.sort() sorts the original and returns None. Choose sorted() when you still need the original order, which is the time order for readings.

ranked = sorted(readings, reverse=True)
print("top 3:", ranked[:3])
print("time order kept:", readings[:3])
Output
top 3: [22.9, 22.5, 22.1]
time order kept: [20.9, 21.9, 21.4]

A tuple is an ordered sequence that cannot change after you create it. Write it with parentheses, or just with commas. Use a tuple for a small record whose fields belong together and have fixed positions: a sensor id and a reading, a latitude and a longitude, a row of a CSV file.

reading = ("2024-05-01T00:00:00", "S1", 20.21, "ok")
print(reading[1], reading[2])
print(len(reading), type(reading))
point = 41.88, -87.63 # the commas make the tuple, not the parentheses
print(point)
Output
S1 20.21
4 <class 'tuple'>
(41.88, -87.63)

A value that cannot change after it is created is immutable. Tuples, strings, numbers, bool and None are immutable. An assignment to a position raises a TypeError:

reading[2] = 20.5
Output
TypeError: 'tuple' object does not support item assignment

Two details catch everyone once:

  • A tuple with one element needs a trailing comma: ("S1",). Without the comma, ("S1") is just the string "S1" in parentheses.
  • The empty tuple is ().

Why use a tuple when a list also works? Three reasons. A tuple tells the reader “this record is complete and fixed”. No code can change it by accident. And a tuple of immutable values can be a dict key or a set element, which a list cannot (see Hashing).

Unpacking assigns the elements of a sequence to several names in one statement. The number of names must match the number of elements.

timestamp, sensor_id, temperature, status = reading
print(sensor_id, temperature, status)
low, high = 19.0, 23.0 # pack two values into a tuple, then unpack it
low, high = high, low # swap without a temporary variable
print(low, high)
Output
S1 20.21 ok
23.0 19.0

A name with a star, such as *middle, collects all the elements that the other names do not take. It always gets a list, which can be empty. This is star-unpacking (extended unpacking). The name _ is a convention for “a value I do not need”.

first, *middle, last = [20.9, 21.9, 21.4, 21.7, 22.1, 22.0]
print(first, middle, last)
header, *rows = ["timestamp,sensor_id,temperature_c", "2024-05-01T00:00:00,S1,20.21"]
print(header)
print(rows)
_, sensor_id, *_ = reading # keep only the second field
print(sensor_id)
Output
20.9 [21.9, 21.4, 21.7, 22.1] 22.0
timestamp,sensor_id,temperature_c
['2024-05-01T00:00:00,S1,20.21']
S1

Unpacking works in a for loop too. Each element of the list is a tuple, and the loop unpacks it into names. enumerate() and zip() from module 03 produce exactly such tuples.

pairs = [("S1", 20.21), ("S2", 22.3), ("S3", 19.4)]
for sensor_id, temperature in pairs:
print(f"{sensor_id}: {temperature:.1f} °C")
Output
S1: 20.2 °C
S2: 22.3 °C
S3: 19.4 °C

A wrong count raises a ValueError:

sensor_id, temperature = ("S1", 20.21, "ok")
Output
ValueError: too many values to unpack (expected 2)

The star also works the other way: inside a list or tuple literal, *items spreads the elements of items into the new container. [*morning, *evening] builds one list from two.

A dictionary (dict) maps keys to values. Each key appears once. You look a value up by its key, not by a position. A pair of a key and its value is an item. Use a dict for a record with named fields, such as one customer, or for a lookup table, such as product id → price.

customer = {
"customer_id": "C00017",
"name": "Mateo Lopez",
"plan": "basic",
"tenure_months": 72,
}
print(customer["name"], customer["plan"])
customer["tenure_months"] += 1 # change a value: one month later
customer["churned"] = False # add a new key
print(customer["tenure_months"], customer["churned"])
print(list(customer))
print(len(customer), "plan" in customer, "email" in customer)
Output
Mateo Lopez basic
73 False
['customer_id', 'name', 'plan', 'tenure_months', 'churned']
5 True False

d[key] raises a KeyError when the key is missing. Real records are often incomplete, so use d.get(key) when a key may be absent. It returns None, or the default that you pass as the second argument.

print(customer.get("email"))
print(customer.get("email", "no email on file"))
Output
None
no email on file
print(customer["email"])
Output
KeyError: 'email'

in tests the keys of a dict, not its values. Three methods give views of the content: keys(), values() and items(). A view is a live, read-only window on the keys, values or items of the dict; it shows later changes to the dict. A for loop over a dict gives the keys. Loop over items() and unpack each pair to get both.

for key, value in customer.items():
print(f"{key:>14}: {value}")
Output
customer_id: C00017
name: Mateo Lopez
plan: basic
tenure_months: 73
churned: False

Since Python 3.7, a dict keeps its keys in insertion order: the order in which you added them. More tools for dicts:

Operation Does
d.pop(key) removes the key and returns its value (KeyError if missing)
d.pop(key, default) the same, but returns default if the key is missing
del d[key] removes the key
d.setdefault(key, default) returns d[key]; first inserts default if the key is missing
d.update(other) / d |= other adds or overwrites the items of other
d1 | d2 a new dict with the items of both; d2 wins on equal keys

The pattern counts[key] = counts.get(key, 0) + 1 counts things: start each key at 0, then add 1. You see it in Example 2.

A set is an unordered collection of unique values. Adding a value that is already there changes nothing. Use a set to remove duplicates, to test membership fast and to compare two groups.

# Product ids sold in store S12 (Denver) on 2024-01-19, one per sales line
basket_log = ["P021", "P015", "P020", "P012", "P017", "P028", "P017"]
sold = set(basket_log)
print(len(basket_log), len(sold))
print(sorted(sold))
print("P017" in sold, "P003" in sold)
Output
7 6
['P012', 'P015', 'P017', 'P020', 'P021', 'P028']
True False

A set has no positions, so sold[0] raises a TypeError. Its print order depends on hashing and can change between runs for strings. Always print sorted(my_set) when the order matters to a reader.

Two sets support the operations of set algebra. Picture two overlapping circles:

Operator Method Result Question it answers
a | b a.union(b) in a or in b Which products sold anywhere?
a & b a.intersection(b) in both Which products sold in both stores?
a - b a.difference(b) in a, not in b Which products sold only in store A?
a ^ b a.symmetric_difference(b) in exactly one Which products sold in one store only?
a <= b a.issubset(b) True if every element of a is in b Are all ordered ids valid catalog ids?
a.isdisjoint(b) True if no common element Do the train and test ids overlap?
# Product ids sold on 2024-06-01 in S01 (Chicago) and S12 (Denver)
chicago = {"P015", "P017", "P019", "P020", "P030"}
denver = {"P020", "P024", "P027"}
print(sorted(chicago | denver))
print(sorted(chicago & denver))
print(sorted(chicago - denver))
print(sorted(chicago ^ denver))
Output
['P015', 'P017', 'P019', 'P020', 'P024', 'P027', 'P030']
['P020']
['P015', 'P017', 'P019', 'P030']
['P015', 'P017', 'P019', 'P024', 'P027', 'P030']

Change a set with add(x), remove(x) (a KeyError if x is missing), discard(x) (no error) and update(items).

A frozenset is an immutable set: frozenset({"vip", "newsletter"}). You need it only when a set must itself be a dict key or a set element.

Nested structures: records, columns and lookups

Section titled “Nested structures: records, columns and lookups”

Containers can hold other containers. This is how real data looks. A JSON file, an API response or a table in memory is a nest of lists and dicts. JSON (JavaScript Object Notation) is a text format for data with the same building blocks: objects (Python dicts), arrays (lists), strings, numbers, true/false and null (None).

The file data/customers.json holds 20 customer records. The json module turns it into Python objects. The with open(...) line opens the file and closes it again at the end; module 07 explains files in detail. For now, copy the two lines.

import json
with open("data/customers.json", encoding="utf-8") as f:
export = json.load(f)
print(type(export), list(export))
customers = export["customers"]
print(type(customers), len(customers))
print(customers[0]["name"], customers[0]["address"]["city"], customers[0]["tags"])
Output
<class 'dict'> ['exported_at', 'count', 'customers']
<class 'list'> 20
Ana Silva Chicago ['mobile_app', 'referral']

export is a dict. Its key "customers" holds a list of 20 dicts. Each customer dict holds a nested dict (address), a list of strings (tags) and a list of dicts (orders). Read a chain of lookups from left to right: customers[0] is the first record, ["address"] its address dict, ["city"] the city string.

flowchart LR
    E["export: dict"] --> C["customers: list"]
    C --> R0["customers[0]: dict"]
    R0 --> N["name: str"]
    R0 --> A["address: dict"]
    A --> CI["city: str"]
    R0 --> T["tags: list of str"]
    R0 --> O["orders: list of dict"]
    O --> O0["order: dict<br/>order_id, date, items, amount"]

Three nested shapes appear again and again:

Shape Example Good for Later in the course
list of dicts (records) [{"id": "C00001", "plan": "premium"}, ...] one dict per row; JSON and APIs pd.DataFrame(records)
dict of lists (columns) {"id": ["C00001", ...], "plan": ["premium", ...]} one list per column; fast column math pd.DataFrame(columns)
dict of dicts (lookup) {"C00001": {"plan": "premium"}, ...} find a record by id at once an index in pandas or SQL

This is the most important idea of the module. An assignment does not copy a value. It makes a name refer to an object. Two names can refer to the same object. Then each name is an alias of the other.

readings = [21.0, 21.9, 21.4]
backup = readings # no copy: a second name for the same list
backup.append(99.9)
print(readings)
print(backup is readings)
Output
[21.0, 21.9, 21.4, 99.9]
True

The list was changed through backup, and readings shows the change, because there is only one list:

flowchart LR
    R["name: readings"] --> L["list object<br/>21.0, 21.9, 21.4, 99.9"]
    B["name: backup"] --> L

A mutable object can change in place: lists, dicts and sets. An immutable object cannot: numbers, strings, tuples, frozenset. Aliasing is harmless for objects that are immutable all the way down, such as a number, a string or a tuple of strings, because nobody can change the shared object. With such a value, every “change” makes a new object and moves the name:

label = "S1"
alias = label
alias += "-north" # makes a new string; label still refers to the old one
print(label, alias)
totals = [100, 200]
same = totals
same += [300] # += on a list extends the SAME list in place
print(totals)
Output
S1 S1-north
[100, 200, 300]

The operator is asks “the same object?”. The operator == asks “equal values?”. Two separate lists can be equal without being the same object:

a = [21.0, 21.9]
b = [21.0, 21.9]
print(a == b, a is b)
Output
True False

A tuple is immutable, but it can hold a mutable object. The tuple cannot change which objects it holds, but a list inside it can still change. Such a tuple is not hashable either (see Hashing):

record = ("S1", [20.21, 20.22])
same = record
same[1].append(20.16) # the tuple is the same, its list has grown
print(record)
print(hash(record))
Output
('S1', [20.21, 20.22, 20.16])
TypeError: unhashable type: 'list'

List repetition with * makes the same trap. [row] * 3 repeats the reference to one inner list, so every “row” is the same list:

grid = [[0] * 3] * 2 # two references to ONE inner list
grid[0][0] = 1
print(grid, grid[0] is grid[1])
grid = [[0] * 3 for _ in range(2)] # a new inner list per row
grid[0][0] = 1
print(grid, grid[0] is grid[1])
Output
[[1, 0, 0], [1, 0, 0]] True
[[1, 0, 0], [0, 0, 0]] False
Type Mutable? Can be a dict key or set element?
int, float, bool, str, None no yes
tuple no yes, if all its elements can
frozenset no yes
list, dict, set yes no

Aliasing is not a bug in Python. It is what makes programs fast: passing a list of a million readings to a function passes one reference, not a million numbers (module 05). The bug appears when you think you have a copy.

A copy is a new container. There are two depths.

A shallow copy makes a new outer container, but the elements inside are the same objects as before. list.copy(), list(x), x[:], dict.copy(), dict(x), set.copy() and copy.copy(x) all make shallow copies. A shallow copy is enough when the elements are immutable, as in a list of numbers.

readings = [21.0, 21.9, 21.4]
backup = readings.copy()
backup.append(99.9)
print(readings, backup)
Output
[21.0, 21.9, 21.4] [21.0, 21.9, 21.4, 99.9]

A deep copy copies the container and, recursively, every mutable object inside it. Use copy.deepcopy(x) for nested records, such as a customer dict with an address dict inside.

import copy
record = {
"name": "Ana Silva",
"address": {"city": "Chicago"},
"tags": ["mobile_app", "referral"],
}
shallow = record.copy()
deep = copy.deepcopy(record)
shallow["name"] = "A. S." # top level: only the shallow copy changes
shallow["address"]["city"] = "Denver" # nested dict: shared with the original!
deep["tags"].append("vip") # deep copy: fully separate
print(record)
print(shallow)
print(deep)
Output
{'name': 'Ana Silva', 'address': {'city': 'Denver'}, 'tags': ['mobile_app', 'referral']}
{'name': 'A. S.', 'address': {'city': 'Denver'}, 'tags': ['mobile_app', 'referral']}
{'name': 'Ana Silva', 'address': {'city': 'Chicago'}, 'tags': ['mobile_app', 'referral', 'vip']}

The shallow copy has its own top-level dict, so the new name did not reach the original. But both dicts point to the same address dict, so the city changed in the original too. The deep copy shares nothing that can change.

flowchart LR
    subgraph S["shallow = record.copy()"]
        R1["record"] --> D1["outer dict 1"]
        S1["shallow"] --> D2["outer dict 2"]
        D1 --> A1["address dict<br/>(shared)"]
        D2 --> A1
    end
    subgraph D["deep = copy.deepcopy(record)"]
        R2["record"] --> D3["outer dict 1"]
        C2["deep"] --> D4["outer dict 3"]
        D3 --> A2["address dict"]
        D4 --> A3["address dict<br/>(copy)"]
    end
You have You want to change Use
a list of numbers or strings the list (add, remove, sort) x.copy()
a dict of simple values the dict d.copy()
a list of dicts, a dict with lists inside anything inside copy.deepcopy(x)
any structure nothing, you only read it no copy at all

A deep copy costs time and memory for big data. Copy only when you will change the data and must keep the original.

A comprehension builds a new list, dict or set from another collection in one expression. It replaces the pattern “make an empty container, loop, append”. Read it as “this expression, for each element, if a condition holds”.

raw = ["21.0", "21.9", "error", "21.4", "", "22.1"]
# The loop version
values = []
for text in raw:
if text.replace(".", "", 1).isdigit():
values.append(float(text))
# The same as a list comprehension
values = [float(text) for text in raw if text.replace(".", "", 1).isdigit()]
print(values)
Output
[21.0, 21.9, 21.4, 22.1]

text.replace(".", "", 1).isdigit() removes one dot and checks that only digits remain, so it accepts "21.4" and rejects "error" and "". It is a simple test that does not accept negative numbers; module 06 shows the robust way with try/except.

The three kinds of comprehension differ only in their brackets:

Kind Syntax Result
list comprehension [expr for x in items if cond] a list, in order, with duplicates
set comprehension {expr for x in items if cond} a set of unique values
dict comprehension {key: value for x in items if cond} a dict
fahrenheit = [round(c * 9 / 5 + 32, 1) for c in values]
cities = {c["address"]["city"] for c in customers}
plan_by_id = {c["customer_id"]: c["plan"] for c in customers[:3]}
print(fahrenheit)
print(len(cities), "cities:", sorted(cities)[:4])
print(plan_by_id)
Output
[69.8, 71.4, 70.5, 71.8]
9 cities: ['Atlanta', 'Chicago', 'Denver', 'Miami']
{'C00001': 'premium', 'C00002': 'standard', 'C00003': 'premium'}

To transform each element in one of two ways, put a conditional expression a if condition else b in the expression part. An if at the end filters; an if ... else at the front chooses a value:

flags = ["high" if v > 21.5 else "ok" for v in values]
print(flags)
Output
['ok', 'high', 'ok', 'high']

A comprehension can have two for parts. They run in the same order as two nested loops. This flattens a list of lists:

amounts = [order["amount"] for c in customers[:2] for order in c["orders"]]
print(amounts)
Output
[32.0, 31.98, 107.98, 1129.08, 24.5, 498.0, 199.94, 263.95]

Use a comprehension when the logic fits on one or two lines. Use a normal loop when you need several steps, print() calls or error handling inside. A comprehension that nobody can read is worse than a loop.

Hashing and big-O: why sets and dicts are fast

Section titled “Hashing and big-O: why sets and dicts are fast”

To answer "P014" in sold_list, Python compares "P014" with each element until it finds a match. With nn elements, that takes up to nn comparisons. To answer "P014" in sold_set, Python computes the hash of "P014": a whole number derived from the value. The hash tells Python where in the set’s internal table to look. It checks one slot (rarely a few) and is done, whatever the size of the set. This internal table is a hash table. Dicts use the same table for their keys.

A value is hashable when it has a hash that never changes. Immutable built-in values are hashable if everything inside them is hashable: ("S1", "00") is, ("S1", [20.21]) is not. Lists, dicts and sets are not hashable, because their content can change. That is why a list cannot be a dict key:

location_by_reading = {["S1", "2024-05-01"]: "server room"}
Output
TypeError: unhashable type: 'list'

Use a tuple instead: {("S1", "2024-05-01"): "server room"} works.

Big-O notation describes how the work of an operation grows with the number of elements nn. It ignores constant factors and keeps the shape of the growth:

Notation Name Meaning Example
O(1)O(1) constant the same time for 10 or 10 million elements x in my_set, d[key], lst[i], lst.append(x)
O(n)O(n) linear 10 times the data, about 10 times the time x in my_list, lst.index(x), lst.insert(0, x), sum(lst)
O(nlog⁡n)O(n \log n) “n log n” a little worse than linear sorted(lst)
O(n2)O(n^2) quadratic 10 times the data, about 100 times the time x in my_list inside a loop over another list

Two fine points. append is O(1)O(1) on average over many calls: now and then the list must grow its storage and copy itself, but that cost spreads out (it is amortized). Set and dict lookups are O(1)O(1) on average; they can slow down when many hashes collide, which almost never happens with ordinary data.

You can measure the difference. The timeit module runs a statement many times and returns the total time in seconds (module 15 covers timing in depth). Here, 5,000 customer ids are stored as a list and as a set, and Python looks for the last id 1,000 times:

import timeit
ids_list = [f"C{n:05d}" for n in range(1, 5001)]
ids_set = set(ids_list)
list_time = timeit.timeit('"C05000" in ids_list', globals=globals(), number=1000)
set_time = timeit.timeit('"C05000" in ids_set', globals=globals(), number=1000)
print("set faster than list:", set_time < list_time)
print("set at least 100x faster:", set_time * 100 < list_time)
Output
set faster than list: True
set at least 100x faster: True

The exact times depend on your computer, so the page prints only the comparison. On a typical laptop, the list needs about 30 milliseconds and the set about 0.02 milliseconds: more than 1,000 times faster. For a list, the time grows with its length. For the set, it does not.

Ask what you will do with the data most often. Then pick the structure that makes that operation cheap.

You need to… Choose Why Membership test x in c
keep values in order, allow duplicates, access by position list ordered, indexable, cheap append O(n)O(n)
keep a fixed record, or use a group of values as a key tuple immutable, hashable, smaller than a list O(n)O(n)
find a value by an id or a name dict key lookup in O(1)O(1) O(1)O(1) (on keys)
keep unique values, test “seen before?”, compare groups set unique, set algebra O(1)O(1)
count how often each value appears dict of counts counts[x] = counts.get(x, 0) + 1 O(1)O(1)
keep rows of a table with named fields list of dict readable, matches JSON
compute on whole columns dict of list one list per column
remove duplicates but keep the first-seen order list(dict.fromkeys(items)) dict keys are unique and ordered
flowchart TD
    Q1{"Find values<br/>by a key or id?"} -- yes --> D["dict"]
    Q1 -- no --> Q2{"Only unique values,<br/>or many 'in' tests?"}
    Q2 -- yes --> S["set"]
    Q2 -- no --> Q3{"A fixed record,<br/>or a dict key?"}
    Q3 -- yes --> T["tuple"]
    Q3 -- no --> L["list"]

For large numeric data, these built-ins are a starting point. NumPy arrays (module 23) and pandas DataFrames (module 24) store millions of numbers far more compactly. The ideas of this module carry over: a DataFrame column behaves like a list, and its index behaves like dict keys. collections adds Counter, defaultdict, deque and namedtuple (module 09).

Example 1 — Clean and summarize a list of sensor readings

Section titled “Example 1 — Clean and summarize a list of sensor readings”

Goal: The first 13 lines of data/readings.txt are the temperatures of sensor S1 in °C, one every 10 minutes from 00:00. Line 12 is broken. Keep the valid readings with their times, compute summary statistics and find the readings above a 22.5 °C alert limit.

raw_lines = ["21.0", "21.9", "21.4", "21.7", "22.1", "22.0", "22.5",
"22.9", "22.2", "22.9", "22.7", "error", "22.4"]
print(len(raw_lines), raw_lines[11], raw_lines[-1])
Output
13 error 22.4

The lines are text, as a file gives them. The list keeps the time order: index 0 is 00:00, index 1 is 00:10 and so on. Module 07 reads these lines from the file for you.

Step 2 — Keep each valid reading with its time

Section titled “Step 2 — Keep each valid reading with its time”
valid = [(i * 10, float(t)) for i, t in enumerate(raw_lines)
if t.replace(".", "", 1).isdigit()]
readings = [temperature for _, temperature in valid]
print(valid[-2:])
print("kept:", len(readings), "skipped:", len(raw_lines) - len(readings))
Output
[(100, 22.7), (120, 22.4)]
kept: 12 skipped: 1

enumerate() runs over the raw lines, so each index is the true position in the file and i * 10 is the true number of minutes after midnight. The if part then drops the broken line before float() sees it. Each kept value is a tuple (minutes, temperature), a small fixed record. The last reading keeps its time, 02:00 (120 minutes), although one line before it was dropped.

n = len(readings)
mean = sum(readings) / n
ordered = sorted(readings)
if n % 2 == 1:
median = ordered[n // 2]
else:
median = (ordered[n // 2 - 1] + ordered[n // 2]) / 2
print(f"n={n} min={min(readings)} max={max(readings)} mean={mean:.2f} median={median}")
Output
n=12 min=21.0 max=22.9 mean=22.14 median=22.15

The median is the middle value of the sorted data. With an odd count it is the element at index n // 2. With an even count it is the mean of the two middle elements. sorted() gives a new list, so readings keeps its time order.

Step 4 — Find the alerts with their times

Section titled “Step 4 — Find the alerts with their times”
alerts = [(minutes, t) for minutes, t in valid if t > 22.5]
for minutes, temperature in alerts:
print(f"{minutes // 60:02d}:{minutes % 60:02d} alert {temperature} °C")
Output
01:10 alert 22.9 °C
01:30 alert 22.9 °C
01:40 alert 22.7 °C

The comprehension unpacks each (minutes, temperature) tuple and keeps the ones above the limit. The loop unpacks each alert again and turns the minutes into a clock time.

Common mistakes:

  • Calling float() on every line before filtering. The broken line raises a ValueError and stops the script.
  • Filtering first and calling enumerate() on the clean list. Every reading after a dropped line then gets a time 10 minutes too early, with no error. Here, the last reading would show 01:50 instead of 02:00. Attach the time (or the line number) before you filter.
  • Sorting the readings with readings.sort() for the median. That destroys the time order. Use sorted().
  • Using ordered[n / 2]. / gives a float, and a list index must be an int: TypeError: list indices must be integers or slices, not float.

Example 2 — Explore customer records in a dict

Section titled “Example 2 — Explore customer records in a dict”

Goal: A marketing analyst receives data/customers.json from the CRM (customer relationship management) system. Count the customers per plan, find the contact details that are missing and build a lookup table by customer id.

import json
with open("data/customers.json", encoding="utf-8") as f:
customers = json.load(f)["customers"]
first = customers[0]
print(len(customers), "records")
print(list(first))
Output
20 records
['customer_id', 'name', 'email', 'signup_date', 'plan', 'address', 'tags', 'orders', 'phone']

list(first) gives the keys of the first record in insertion order. Always look at the keys of one record before you write code for all of them.

plan_counts = {}
for c in customers:
plan_counts[c["plan"]] = plan_counts.get(c["plan"], 0) + 1
print(plan_counts)
print(sum(plan_counts.values()) == len(customers))
Output
{'premium': 6, 'standard': 7, 'basic': 7}
True

plan_counts.get(plan, 0) returns the count so far, or 0 the first time a plan appears. The check at the end proves that every customer was counted once.

no_phone = [c["customer_id"] for c in customers if c.get("phone") is None]
no_postal = [c["customer_id"] for c in customers if "postal_code" not in c["address"]]
print("no phone:", len(no_phone))
print("no postal code:", no_postal)
Output
no phone: 14
no postal code: ['C00005', 'C00014']

The phone key is absent from most records and null in one, and c.get("phone") returns None in both cases. "postal_code" not in c["address"] tests the keys of the nested address dict. c["phone"] would have crashed on the first record without a phone.

by_id = {c["customer_id"]: c for c in customers}
mateo = by_id["C00017"]
print(mateo["name"], mateo["address"]["city"], len(mateo["orders"]), "orders")
print(by_id["C00017"] is customers[16])
Output
Mateo Lopez Minneapolis 2 orders
True

The dict comprehension maps each id to its record. A lookup by id is now one step, not a scan of 20 records. The is check shows that the dict holds references to the same record dicts, not copies.

Common mistakes:

  • Using c["phone"] on optional fields. Use c.get("phone") and decide what None means.
  • Testing "Chicago" in customer. in on a dict checks the keys, so this is False even for a Chicago customer. Test customer["address"]["city"] == "Chicago".
  • Changing a record through by_id and being surprised that customers changed too. Both hold the same dicts.

Example 3 — Compare product id sets across stores

Section titled “Example 3 — Compare product id sets across stores”

Goal: A category manager wants to know which of the 30 catalog products sold in store S01 (Chicago) or S12 (Denver) in the week of 2024-03-04, which sold in both and which did not sell at all. The logs come from data/sales.csv and hold one product id per sales line, so ids repeat.

Step 1 — Build the catalog with a set comprehension

Section titled “Step 1 — Build the catalog with a set comprehension”
catalog = {f"P{n:03d}" for n in range(1, 31)}
print(len(catalog), sorted(catalog)[:3], sorted(catalog)[-1])
Output
30 ['P001', 'P002', 'P003'] P030

The ids in data/products.csv run from P001 to P030. The format spec :03d pads the number to 3 digits. A set comprehension builds the set directly.

# Product ids of every sales line, 2024-03-04 to 2024-03-10 (data/sales.csv)
chicago_log = ["P022", "P002", "P017", "P002", "P017", "P021", "P005", "P013", "P003",
"P011", "P024", "P001", "P010", "P018", "P028", "P010", "P020", "P005",
"P001", "P011", "P027", "P026", "P016", "P021", "P007"]
denver_log = ["P010", "P005", "P028", "P009"]
chicago = set(chicago_log)
denver = set(denver_log)
print("Chicago:", len(chicago_log), "lines ->", len(chicago), "distinct products")
print("Denver:", len(denver_log), "lines ->", len(denver), "distinct products")
print(sorted(denver))
Output
Chicago: 25 lines -> 18 distinct products
Denver: 4 lines -> 4 distinct products
['P005', 'P009', 'P010', 'P028']

set() drops the duplicates. The length of the set is the number of distinct products, which a manager means by “how many products sold”.

print("both:", sorted(chicago & denver))
print("only Chicago:", len(chicago - denver), "products")
print("only Denver:", sorted(denver - chicago))
print("anywhere:", len(chicago | denver))
Output
both: ['P005', 'P010', 'P028']
only Chicago: 15 products
only Denver: ['P009']
anywhere: 19

Each question is one operator. Without sets, each would be a nested loop with in tests on lists.

Step 4 — Find the products that did not sell

Section titled “Step 4 — Find the products that did not sell”
unsold = catalog - (chicago | denver)
print(len(unsold), "unsold, e.g.", sorted(unsold)[:5])
print("all sold ids are valid:", (chicago | denver) <= catalog)
Output
11 unsold, e.g. ['P004', 'P006', 'P008', 'P012', 'P014']
all sold ids are valid: True

The difference with the catalog gives the products without a sale. The subset test <= is a validation check: an id outside the catalog would point to a typo in the log.

Common mistakes:

  • Printing a set of strings directly. The order can change from run to run. Print sorted(s).
  • Writing chicago + denver. Sets have no +: TypeError: unsupported operand type(s) for +: 'set' and 'set'. Use |.
  • Starting an empty set with {}. That is an empty dict, and .add() then fails with AttributeError: 'dict' object has no attribute 'add'.

Example 4 — Use tuples as records and unpack them

Section titled “Example 4 — Use tuples as records and unpack them”

Goal: Rows from data/sensors.csv arrive as tuples (timestamp, sensor_id, temperature_c, status). Find the hottest reading, the readings with a non-ok status and the mean temperature per sensor and hour.

Step 1 — Store the rows as a list of tuples

Section titled “Step 1 — Store the rows as a list of tuples”
header, *rows = [
("timestamp", "sensor_id", "temperature_c", "status"),
("2024-05-01T00:00:00", "S1", 20.21, "ok"),
("2024-05-01T00:00:00", "S2", 22.3, "ok"),
("2024-05-01T00:10:00", "S1", 20.22, "ok"),
("2024-05-01T00:10:00", "S2", 22.44, "ok"),
("2024-05-01T00:40:00", "S2", 38.03, "warn"),
("2024-05-01T01:00:00", "S1", 20.11, "ok"),
]
print(header)
print(len(rows), "rows; first:", rows[0])
Output
('timestamp', 'sensor_id', 'temperature_c', 'status')
6 rows; first: ('2024-05-01T00:00:00', 'S1', 20.21, 'ok')

Star-unpacking splits the header from the data rows in one line. rows is a list, because a starred name always collects a list.

hottest_temp, hottest_sensor, hottest_time = max(
(temp, sensor, ts) for ts, sensor, temp, _ in rows
)
print(f"{hottest_sensor} at {hottest_time}: {hottest_temp} °C")
Output
S2 at 2024-05-01T00:40:00: 38.03 °C

Tuples compare element by element, from left to right. Putting the temperature first makes max() compare temperatures. The loop part unpacks each row and ignores the status with _. The expression in parentheses without square brackets is a generator expression: a lazy comprehension that max() consumes one value at a time (module 10).

problems = [(ts, sensor, status) for ts, sensor, _, status in rows if status != "ok"]
print(problems)
Output
[('2024-05-01T00:40:00', 'S2', 'warn')]

Unpacking in the comprehension gives each field a name. ts, sensor and status read much better than row[0], row[1] and row[3].

groups = {}
for ts, sensor, temp, _ in rows:
key = (sensor, ts[11:13]) # (sensor id, hour as text)
groups.setdefault(key, []).append(temp)
for (sensor, hour), temps in sorted(groups.items()):
mean = sum(temps) / len(temps)
print(f"{sensor} hour {hour}: mean {mean:.2f} °C from {len(temps)}")
Output
S1 hour 00: mean 20.21 °C from 2
S1 hour 01: mean 20.11 °C from 1
S2 hour 00: mean 27.59 °C from 3

A tuple of two strings is hashable, so it can be a dict key. setdefault(key, []) returns the list for the key, and first inserts an empty list if the key is new. sorted(groups.items()) sorts the pairs by key, and the loop unpacks the nested tuple ((sensor, hour), temps).

Common mistakes:

  • Unpacking with the wrong number of names: ts, sensor, temp = row on a 4-field row raises ValueError: too many values to unpack (expected 3).
  • Using a list such as [sensor, hour] as the key. Lists are unhashable: TypeError: unhashable type: 'list'.
  • Writing groups.setdefault(key, []) + [temp]. That builds a new list and throws it away. append() changes the list inside the dict.

Example 5 — Remove personal data without damaging the original

Section titled “Example 5 — Remove personal data without damaging the original”

Goal: A data engineer must share customer records with an outside analytics partner. The shared version must not contain names, emails, phone numbers or the street, city and postal code of the address; only the region stays. The original records must stay complete, because the CRM pipeline still uses them.

Step 1 — Load two records and try a plain assignment

Section titled “Step 1 — Load two records and try a plain assignment”
import copy
import json
with open("data/customers.json", encoding="utf-8") as f:
original = json.load(f)["customers"][:2]
shared = original # an alias, not a copy
shared[0]["name"] = "REDACTED"
print(original[0]["name"])
Output
REDACTED

shared is a second name for the same list, so the “redacted” name is now in the original. Reload the data and try again.

with open("data/customers.json", encoding="utf-8") as f:
original = json.load(f)["customers"][:2]
personal = ["name", "email", "phone"]
shared = [c.copy() for c in original] # a new dict per record
for c in shared:
for field in personal:
c.pop(field, None) # None: no error when a record has no phone
for field in ["street", "city", "postal_code"]:
c["address"].pop(field, None)
print(list(original[0])[:3], "phone" in original[0])
print(original[0]["address"])
Output
['customer_id', 'name', 'email'] True
{'region': 'North'}

Each record is a new dict, so pop() did not touch the top level of the originals: they still have name, email and phone. But address is a nested dict, and the shallow copy shares it. The original address has lost its street, city and postal code. A shallow copy only protects the top level.

with open("data/customers.json", encoding="utf-8") as f:
original = json.load(f)["customers"][:2]
shared = copy.deepcopy(original)
for c in shared:
for field in personal:
c.pop(field, None)
c["address"] = {"region": c["address"]["region"]}
print(original[0]["name"], original[0]["address"]["city"], original[0]["phone"])
print(list(shared[0]), shared[0]["address"])
Output
Ana Silva Chicago +1-555-908-5284
['customer_id', 'signup_date', 'plan', 'address', 'tags', 'orders'] {'region': 'North'}

copy.deepcopy() copies the list, every record dict and every dict and list inside them. Changes to shared cannot reach original. Replacing address with a new one-key dict is the simplest way to keep only the region.

s, o = shared[0], original[0]
print(s is o, s["tags"] is o["tags"], s["orders"] is o["orders"])
print(any(a is b for a, b in zip(s["orders"], o["orders"])))
print(s["orders"] == o["orders"])
Output
False False False
False
True

is shows that no container is shared: not the record, not the tags list, not the orders list and not one of the order dicts inside it. == shows that the orders are still equal in value. This pair of checks is a quick test for any copy.

The shared records still carry customer_id. The partner cannot read a name, but the CRM team can link each record back to a person. Such data is pseudonymized, not anonymous. Real anonymization also replaces or drops the id and checks that rare combinations of the remaining fields do not identify anyone.

Common mistakes:

  • Believing that list(records) or records[:] copies the records. It copies only the outer list. The dicts inside are shared.
  • Using copy.deepcopy() everywhere “to be safe”. For a large dataset it doubles the memory and costs time. Copy only what you will change.
  • Using c.pop("phone") without a default. Most records have no phone, so the first one raises KeyError: 'phone'.

Example 6 — Reshape records with comprehensions

Section titled “Example 6 — Reshape records with comprehensions”

Goal: Turn the customer records into the shapes that later tools expect: a dict of columns for analysis, a spend total per customer and a flat list of orders.

fields = ["customer_id", "plan", "signup_date"]
columns = {field: [c[field] for c in customers] for field in fields}
print(list(columns))
print(columns["plan"][:5])
print(len(columns["customer_id"]))
Output
['customer_id', 'plan', 'signup_date']
['premium', 'standard', 'premium', 'premium', 'basic']
20

The dict comprehension has a list comprehension as its value. For each field name, it collects that field from every record. This is the shape that pd.DataFrame(columns) accepts in module 24.

rows = [dict(zip(columns, values)) for values in zip(*columns.values())]
print(rows[0])
print(rows[0] == {f: customers[0][f] for f in fields})
Output
{'customer_id': 'C00001', 'plan': 'premium', 'signup_date': '2018-12-01'}
True

zip(*columns.values()) uses the star to pass the three column lists to zip() as three separate arguments. zip() then yields one tuple per row. zip(columns, values) pairs each field name with its value, and dict() turns the pairs into a record.

spend = {c["customer_id"]: round(sum(o["amount"] for o in c["orders"]), 2)
for c in customers}
big = {cid: total for cid, total in spend.items() if total > 1500}
print(big)
print("top spender:", max(spend, key=spend.get))
Output
{'C00003': 2070.07, 'C00017': 2324.98, 'C00019': 1763.46}
top spender: C00017

The generator expression from Example 4 feeds the order amounts of one customer to sum(). The sum of nothing is 0, so customers without orders get 0. The second comprehension filters a dict by its values. max(spend, key=spend.get) compares the keys by their values; module 05 explains key functions.

orders = [(c["customer_id"], o["order_id"], o["amount"])
for c in customers for o in c["orders"]]
print(len(orders), "orders")
print(orders[:3])
Output
48 orders
[('C00001', 'O000614', 32.0), ('C00001', 'O004814', 31.98), ('C00001', 'O004967', 107.98)]

Two for parts flatten the nested lists: the outer loop runs over customers, the inner over that customer’s orders. The result is one tuple per order, a “long” table that is easy to filter and sum.

Common mistakes:

  • Swapping the two for parts: [o for o in c["orders"] for c in customers] raises a NameError, because c does not exist yet when the first part runs.
  • Expecting a dict comprehension to keep duplicate keys. A later key overwrites an earlier one silently.
  • Packing too much into one comprehension. If you need a comment to explain it, write a loop.

Example 7 — Choose a structure for a fast lookup

Section titled “Example 7 — Choose a structure for a fast lookup”

Goal: A web shop’s order service must reject orders with an unknown customer id, such as a typo from a form. The valid ids are those of the 5,000 customers in data/customers.csv: C00001 to C05000. The check runs for every order, so it must be fast. Compare a list and a set, and confirm that both give the same answers.

known_list = [f"C{n:05d}" for n in range(1, 5001)]
known_set = set(known_list)
incoming = ["C00017", "C04990", "C50000", "C4990"]
print(len(known_list), known_list[:2], known_list[-1])
Output
5000 ['C00001', 'C00002'] C05000

The ids in the file run from 1 to 5,000 with 5 digits, so a comprehension rebuilds them exactly. A set of the same ids takes one line. The last two incoming ids are typos.

Step 2 — Check that both structures agree

Section titled “Step 2 — Check that both structures agree”
from_list = [cid in known_list for cid in incoming]
from_set = [cid in known_set for cid in incoming]
print(from_list)
print(from_list == from_set)
Output
[True, True, False, False]
True

The answers are identical. The choice of structure changes the speed, not the result. Always check this when you optimize code.

import timeit
checks = incoming * 250 # 1,000 order checks
list_time = timeit.timeit(
"[cid in known_list for cid in checks]", globals=globals(), number=5
)
set_time = timeit.timeit(
"[cid in known_set for cid in checks]", globals=globals(), number=5
)
print("set is faster:", set_time < list_time)
print("set is at least 50x faster:", set_time * 50 < list_time)
Output
set is faster: True
set is at least 50x faster: True

The list scans up to 5,000 ids for every check: O(n)O(n) per check, so 1,000 checks cost up to 5 million comparisons. The set computes one hash per check: O(1)O(1). The gap grows with the number of customers.

Step 4 — Count the work instead of the time

Section titled “Step 4 — Count the work instead of the time”
comparisons = [
known_list.index(cid) + 1 if cid in known_set else len(known_list)
for cid in incoming
]
print("list comparisons per check:", comparisons)
print("list total:", sum(comparisons), "set lookups:", len(incoming))
Output
list comparisons per check: [17, 4990, 5000, 5000]
list total: 15007 set lookups: 4

A found id costs as many comparisons as its position plus one. A missing id costs a scan of the whole list, so the typos are the most expensive checks. The set needs one hash lookup per check. Counting the work explains the timing without a stopwatch.

Common mistakes:

  • Converting the list to a set inside the loop, as in cid in set(known_list). That builds a new set (an O(n)O(n) step) for every check and is slower than the list.
  • Using a set when the order or the duplicates matter. A set forgets both.
  • Trusting one timing run. Timings vary; compare with a large factor, or count the operations.
Mistake Symptom Fix
backup = readings, then changing backup The “original” changes too backup = readings.copy()
A shallow copy of nested records Nested dicts or lists change in the original copy.deepcopy(records)
result = readings.sort() result is None result = sorted(readings), or call readings.sort() on its own line
readings.append([22.9, 22.2]) A list inside the list: [..., [22.9, 22.2]] readings.extend([22.9, 22.2])
customer["phone"] on an optional key KeyError: 'phone' customer.get("phone")
"Chicago" in customer False, because in checks the keys Test the value: customer["address"]["city"] == "Chicago"
empty = {} to start a set AttributeError: 'dict' object has no attribute 'add' empty = set()
("S1") as a one-element tuple It is the string 'S1' ("S1",)
A list as a dict key or set element TypeError: unhashable type: 'list' Use a tuple
Printing a set of strings in a report The order changes between runs sorted(my_set)
grid = [[0] * 3] * 3, then grid[0][0] = 1 Every row changes grid = [[0] * 3 for _ in range(3)]
Removing elements from a list while you loop over it Some elements are skipped Build a new list with a comprehension
Adding keys to a dict while you loop over it RuntimeError: dictionary changed size during iteration Loop over list(d) or build a new dict
x in big_list inside a loop The script slows to a crawl as data grows Convert to a set once, before the loop
a, b = row with the wrong number of fields ValueError: too many values to unpack Match the names to the fields, or use *rest
  • Web development: a JSON request body becomes a dict of dicts and lists. A web framework reads request["items"][0]["quantity"], and a set of allowed roles decides if a user may call an endpoint.
  • Automation: a backup script keeps a set of file names it has already copied, so a second run skips them in O(1)O(1) per file.
  • Configuration: a tool merges default settings with user settings in one expression: settings = defaults | user_settings. | builds a new dict and leaves defaults unchanged; deep-copy the defaults only if you will change nested settings.
  • Tooling: a linter keeps a dict that maps each rule code to its message, and a tuple (file, line, column) for each finding, sorted for the report.
  • A list is ordered and changeable: use it for sequences such as readings in time order. sorted() returns a new list; .sort() changes the list and returns None.
  • A tuple is ordered and immutable: use it for fixed records and as a dict key. One element needs a trailing comma.
  • Unpacking gives each element a name. *rest collects the remaining elements in a list. _ marks values you ignore.
  • A dict maps unique keys to values and keeps insertion order. Use d.get(key, default) for optional keys. in tests the keys.
  • A set holds unique values. Membership is O(1)O(1). |, &, - and ^ compare groups. set() is the empty set.
  • Names refer to objects. Two names can be aliases of one mutable object. A shallow copy copies one level; copy.deepcopy() copies every level.
  • Comprehensions build lists, sets and dicts in one expression: [expr for x in items if cond].
  • Choose the structure by the operation you need most: position → list, fixed record → tuple, lookup by key → dict, uniqueness and membership → set.

Q1. What is the difference between readings.sort() and sorted(readings)?

Answer

readings.sort() sorts the list in place and returns None. sorted(readings) returns a new sorted list and leaves readings unchanged. Use sorted() when you still need the original order.

Q2. What is type(("S1")), and how do you write a tuple with only the element "S1"?

Answer

<class 'str'>. Parentheses alone only group an expression. The comma makes the tuple: ("S1",) or "S1",.

Q3. What do first, middle and last hold after first, *middle, last = [3, 5]?

Answer

first is 3, last is 5 and middle is [], an empty list. A starred name always gets a list, even when no elements are left for it.

Q4. A record may or may not have the key "phone". Why is record.get("phone") better than record["phone"]?

Answer

record["phone"] raises a KeyError when the key is missing and stops the script. record.get("phone") returns None (or a default you choose, as in record.get("phone", "unknown")), so the code can handle the gap.

Q5. a = [1, 2], b = a, b.append(3). What is a? Why?

Answer

[1, 2, 3]. b = a does not copy the list. It makes b a second name (an alias) for the same list, so a change through b is visible through a.

Q6. When is a shallow copy not enough?

Answer

When the container holds mutable objects that you will change, such as a list of dicts or a dict with a nested address dict. A shallow copy makes a new outer container, but the inner objects are shared. Use copy.deepcopy().

Q7. Why can a tuple be a dict key but a list cannot?

Answer

A dict finds a key through its hash, which must never change. A tuple of immutable values is immutable, so its hash is fixed. A list can change, so it has no hash: TypeError: unhashable type: 'list'.

Q8. You must check 100,000 order ids against a list of 50,000 known ids. What do you change, and why?

Answer

Convert the known ids to a set once: known = set(known_ids). A membership test on a list is O(n)O(n) and scans up to 50,000 ids per check. A membership test on a set is O(1)O(1). The whole job goes from up to 5 billion comparisons to about 100,000 hash lookups.

Q9. Write a comprehension that maps each product id to its price, only for prices above 100, from prices = {"P001": 79.99, "P003": 1299.0, "P006": 349.0}.

Answer

{pid: price for pid, price in prices.items() if price > 100} gives {'P003': 1299.0, 'P006': 349.0}. It is a dict comprehension that unpacks each item and filters with if.

Q10. What is wrong with tags = {} followed by tags.add("vip")?

Answer

{} is an empty dict, not an empty set, and a dict has no add method: AttributeError: 'dict' object has no attribute 'add'. Write tags = set().

Q11. You need the distinct cities of the customers in the order they first appear. Why does set(cities) not do it, and what does?

Answer

A set has no order. list(dict.fromkeys(cities)) keeps the first-seen order, because dict keys are unique and keep insertion order.

Your progress

0 / 4 done

  • Exercises: 28 exercises on lists, tuples, dicts, sets, unpacking, copies and comprehensions, with hints and full solutions.
  • Mini-project: audit the customer records of data/customers.json for consistency, gaps, geography and order patterns, and build a safe pseudonymized export.
  • Cheat sheet: every method, operator and complexity of the four structures on one page.
  • Next module: 05. Functions packs your code into reusable functions with parameters, return values and key functions for sorted().