List, dict, set, and tuple reference
Core collection methods, when to use each type, and a speed note on membership.
Why it matters: Wrong collection choice is a common slowdown. Set membership is fast; list scans are not.
Basics
Pick the right type
- list - ordered, mutable, allows duplicates
- tuple - ordered, immutable (can be a dict key)
- dict - key to value map
- set - unique items, fast
inchecks
If you write if item in big_list inside a loop, convert to a set first.
Tiny example
List vs set for labels.
labels = ["spam", "ham", "spam"]
unique = set(labels)
print(len(labels), "rows,", len(unique), "classes")Basics
List and tuple
List: append, extend, insert, remove, pop, sort, reverse, copy.
sort() returns None. sorted() returns a new list. Do not write items = items.sort().
Tuple has mostly count and index. Unpack with a, b = pair or first, *rest = items.
Tiny example
Append, sort a copy, unpack a tuple.
scores = [0.4, 0.9]
scores.append(0.7)
print(sorted(scores))
model, lr = ("mini", 2e-5)
print(model, lr)Basics
Dict and set
Dict: get, items, update, setdefault, pop. Merge with a | b (3.9+).
Set: add, discard, | & - ^.
{} is an empty dict. Use set() for an empty set.
Tiny example
get, setdefault, and set intersection.
counts = {"spam": 3}
print(counts.get("ham", 0))
counts.setdefault("ham", 0)
a, b = {"rag", "eval"}, {"eval", "agents"}
print(a & b)Then AI / ML
AI / ML examples
Same idea, used in real AI work. Press Try in lab to run it.
AI / ML example
AI / ML: feature set diff
Set ops compare train vs serving columns fast.
In AI / ML: Training/serving skew checks often use set difference.
example.py
Python
train = {"tokens", "latency", "model", "region", "user_id"}
serve = {"tokens", "latency", "model", "device"}
print("both:", sorted(train & serve))
print("train only:", sorted(train - serve))
print("serve only:", sorted(serve - train))AI / ML example 2
AI / ML: group events with setdefault
Build a dict of lists without KeyError.
In AI / ML: Telemetry and agent traces often group by session id.
example.py
Python
events = [("u1", "click"), ("u2", "view"), ("u1", "buy")]
by_user = {}
for user, action in events:
by_user.setdefault(user, []).append(action)
print(by_user)
print("busiest:", max(by_user.items(), key=lambda p: len(p[1]))[0])Takeaways
- 1Use a set for membership tests on large data.
- 2sort() mutates and returns None; sorted() returns a list.
- 3dict.get and setdefault avoid KeyError.