Data Structures: Lists, Tuples, Dicts and Sets
Lists: ordered, changeable
tasks = ["write tests", "fix bug"]
tasks.append("deploy")
tasks.insert(0, "plan")
tasks.remove("fix bug")
last = tasks.pop()
tasks.sort()
tasks[0] tasks[-1] tasks[1:3]
len(tasks)
Tuples: ordered, fixed
point = (3, 4)
x, y = point # unpacking
def min_max(values):
return min(values), max(values) # returns a tuple
low, high = min_max([4, 1, 9])
Use tuples for records that should not change and as dictionary keys.
Dictionaries: key → value
user = {"name": "Ada", "role": "admin", "points": 120}
user["email"] = "ada@example.com" # add / update
user.get("phone", "not set") # safe lookup with default
del user["role"]
for key, value in user.items():
print(key, value)
"name" in user # key check
Dicts keep insertion order and lookups are very fast, whatever their size.
Sets: unique, unordered
tags = {"python", "flask", "python"} # {'python', 'flask'}
a = {"python", "sql"}; b = {"python", "docker"}
a & b # intersection {'python'}
a | b # union
a - b # difference {'sql'}
Converting a list to a set is the fastest way to remove duplicates or test membership in large collections.
Choosing
| Need | Use |
|---|---|
| ordered items you add/remove | list |
| fixed record, function returning several values | tuple |
| look up by name or id | dict |
| uniqueness, membership tests | set |
Nested data (like JSON)
order = {
"id": 1001,
"customer": {"name": "Ada", "email": "ada@example.com"},
"items": [
{"sku": "HOOD-1", "qty": 2, "price": 39.0},
{"sku": "MUG-3", "qty": 1, "price": 12.5},
],
}
total = sum(i["qty"] * i["price"] for i in order["items"])
The collections module
from collections import Counter, defaultdict
Counter("mississippi").most_common(2) # [('i', 4), ('s', 4)]
by_role = defaultdict(list)
for u in users:
by_role[u["role"]].append(u["name"])
A common trap: mutable copies
a = [1, 2, 3]
b = a # same list!
b.append(4) # a is now [1, 2, 3, 4]
c = a.copy() # independent copy
Exercise
Given a list of order dicts, compute revenue per customer with a defaultdict(float), then print the top three customers.
Check yourself
- When would you choose a set over a list?
- Why does
b = anot copy a list? - What does
dict.get(key, default)protect against?
Ihr Fortschritt wird nur in diesem Browser gespeichert.
Zur Prüfung einreichen (10 Punkte)