--- Syntax And Data Structures • Python Cabinet

Syntax And Data Structures

  • Reach for lists when order matters, dicts when you look things up by name, sets when you need unique items, and f-strings whenever you format text.

How it works

The four everyday building blocks you’ll reuse in almost every script:

# Lists (ordered, mutable) & comprehensions
scores = [0.42, 0.81, 0.65]
passing = [s for s in scores if s >= 0.60]

# Dicts (key -> value) with safe .get() lookup
policy = {"allowance": 65, "currency": "USD"}
limit = policy.get("allowance", 0)

# Loop with index (enumerate) or key+value (.items)
for idx, score in enumerate(passing, start=1):
    print(f"Match #{idx}: {score:.2f}")

for key, value in policy.items():
    print(f"{key} = {value}")

Use dict.get("key", default) when a key might be missing—it avoids a KeyError crash. Use set(items) to deduplicate a list or check membership (if item in seen:) in constant time.

What can go wrong

  • Bare dict["key"] on untrusted data: Crashes with KeyError if the field is absent; use .get() for optional keys.
  • Mutating a list while looping over it: Removing items from a list inside for x in items: skips elements. Build a new list with a comprehension instead.
  • Mutable default arguments: Never write def add_item(items=[]):—that single list is shared across every call. Use items: list | None = None and set items = items or [] inside.

Evidence: Python 3 standard library reference and Automate the Boring Stuff core patterns (general language reference, not tied to one lab file). Related: Files and paths with pathlib.