Data structures & comprehensions
Python has four built-in collections, and choosing the right one makes code simpler and faster. The question to ask is: does order matter, can it change, and do I look things up by position or by name?
list: an ordered, changeable sequence
Use a list when you have several items in order and might add or remove some. Items can be any type.
servers = ["web-01", "web-02"]
servers.append("web-03") # add to the end
servers.insert(0, "lb-01") # add at a position
servers.remove("web-02") # remove by value
last = servers.pop() # remove and return the last one
servers.sort() # sort in place
len(servers) # how many
tuple: an ordered sequence that can't change
A tuple, written with brackets ( ), is like a list you can't modify. Use it for fixed groups of values, like coordinates or a (host, port) pair. Because it can't change, a tuple can be a dict key; a list can't.
dict: look things up by key
A dictionary stores key: value pairs and finds a value by its key instantly, however big it gets. It's the natural shape for configuration, JSON data and counting things.
config = {"host": "db-01", "port": 5432}
config["port"] # 5432
config["user"] = "app" # add or change a key
config.get("password") # None instead of an error if missing
config.get("timeout", 30) # with a default
for key, value in config.items():
print(key, "=", value)
set: unique items, no order
A set keeps only one copy of each item and is fast at "is this in there?" checks. set(ip_list) removes duplicates in one step, and sets support maths: a | b (union), a & b (items in both), a - b (in a but not b).
Comprehensions: building a collection in one line
A comprehension creates a new list (or dict or set) by looping over something, optionally filtering, and transforming each item. It reads as "give me this for each item in that, if condition":
squares = [x * x for x in range(5)] # [0, 1, 4, 9, 16]
evens = [x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8]
names = [s.upper() for s in servers]
ports = {name: 8000 + i for i, name in enumerate(servers)} # dict comprehension
enumerate() gives you the position and the item together (for i, item in enumerate(items)), and zip(a, b) walks two lists side by side.
Nested data: what APIs and configs really look like
Real data is collections inside collections. A list of servers from an API, a JSON file or a YAML config usually looks like this, a list of dicts:
servers = [
{"name": "web-01", "env": "prod", "cpu": 35, "tags": ["nginx"]},
{"name": "web-02", "env": "prod", "cpu": 91, "tags": ["nginx", "canary"]},
{"name": "db-01", "env": "dev", "cpu": 12, "tags": []},
]
servers[1]["name"] # 'web-02': position 1 in the list, then the "name" key
servers[1]["tags"][0] # 'nginx'
for s in servers:
if s["cpu"] > 80:
print(s["name"], "is busy")
prod = [s["name"] for s in servers if s["env"] == "prod"] # ['web-01', 'web-02']
Read access paths left to right, one step at a time: servers[1] is a dict, so ["tags"] is a list, so [0] is its first item. When a key might be missing, s.get("owner", "nobody") avoids a KeyError.
Copying versus sharing
Assigning a list to another name doesn't copy it; both names point at the same list:
a = ["web-01"]
b = a
b.append("web-02")
print(a) # ['web-01', 'web-02']: a changed too!
c = a.copy() # a real, separate copy (or list(a))
This surprises everyone once. If a function changes a list you passed in, the caller sees the change.
Sorting and counting
by_cpu = sorted(servers, key=lambda s: s["cpu"], reverse=True) # busiest first
by_cpu[0]["name"] # 'web-02'
from collections import Counter
levels = ["INFO", "ERROR", "INFO", "WARN", "ERROR", "ERROR"]
Counter(levels) # Counter({'ERROR': 3, 'INFO': 2, 'WARN': 1})
Counter(levels).most_common(1) # [('ERROR', 3)]
sorted() returns a new list and leaves the original alone; list.sort() sorts in place and returns None. The key is a small function that says what to sort by; lambda s: s["cpu"] is a one-line function that takes a server and returns its CPU.
Try it yourself
From the
serverslist above, make a list of the names of servers that have the tag"nginx".Show an answer
[s["name"] for s in servers if "nginx" in s["tags"]]Count how many lines in
linescontain"ERROR", without usingCounter.Show an answer
errors = 0 for line in lines: if "ERROR" in line: errors += 1Or in one line:
sum(1 for line in lines if "ERROR" in line).Remove duplicate IP addresses from a list but keep the order they first appeared in.
Show an answer
unique = list(dict.fromkeys(ips))A
setwould remove duplicates too, but forgets the order. Dict keys keep it.