Core Data Structures
Four structures run 90% of all Python code. Master these and every LLM library will feel familiar.
▶ Watch this reelWhat you'll learn
- list & tuple
- dict — the hash map
- set — unique & fast
- Comprehensions
- Slicing & unpacking
Remember this
- list = mutable sequence, tuple = immutable record, dict = the JSON-shaped hash map
- Comprehensions are LINQ in one line — [x for x in items if cond]
- Slicing is half-open (start inclusive, end exclusive); unpacking + *rest replaces index plumbing
list & tuple
list [1,2] | tuple (1,2) | |
|---|---|---|
| Mutable | ✅ append/insert/remove/sort | ❌ frozen |
| Hashable (usable as dict key) | ❌ | ✅ |
| Use for | evolving collections | fixed records |
dict
- Hash map:
{"key": value}— keys must be hashable (str, number, tuple). - O(1) lookup/insert/delete.
d.get(k, default)— safe read ·d.items()— iterate pairs ·d.keys()/d.values().- Every JSON object becomes a dict — this is the LLM-era structure.
set
- Unordered unique items; O(1) membership.
|union ·&intersection ·-difference.list(set(x))dedupes (order lost) ·dict.fromkeys(x)dedupes, keeps order.
Comprehensions
[m.upper() for m in models] # select
[m for m in models if "gpt" in m] # where
[m.upper() for m in models if "gpt" in m] # both
{m: len(m) for m in models} # dict comp
One line max — longer means go back to a loop.
Slicing & unpacking
a[1:3]= indexes 1,2 (half-open) ·a[:3]·a[-2:](last two).first, *rest = items·a, b = b, a(swap).
Code: The four structures + comprehensions in action
models = ["gpt-4o", "claude-sonnet", "gpt-4o-mini", "llama-3"]
# list: mutable sequence
models.append("gemini-flash")
models.sort()
# tuple: immutable record
endpoint = ("api.openai.com", 443) # host, port — fixed
host, port = endpoint # unpacked in one line
# dict: the structure of every LLM API response
response = {"model": "gpt-4o", "tokens": 42, "ok": True}
model = response.get("model", "unknown")
for key, value in response.items():
print(f" {key}: {value}")
# set: dedupe + instant membership
tags = list({"ai", "python", "ai", "rag"}) # → ['ai', 'python', 'rag']
# comprehension = LINQ in one line
gpts = [m.upper() for m in models if "gpt" in m]
lengths = {m: len(m) for m in models}
# slicing & unpacking
first, *rest = models
last_two = models[-2:]