N
NexusDigitalLabs
← Back to Academy

Phase 1 — Foundations · Lesson 2 · 20 XP

Python core I: types, data structures, comprehensions

Four collections cover almost everything: list (ordered, mutable, duplicates OK), tuple (ordered, immutable — good for fixed records like (x, y)), dict (lookup by key), and set (unique, unordered, fast membership tests). JSON — which is most of what an LLM API returns — is just nested dicts and lists, so this is the most-used chapter of the whole course.

user = {"name": "Dilan", "age": 30}
user.get("email", "n/a")   # "n/a" — no KeyError

seen = set()
seen.add("x")
"x" in seen                # True, and fast even for huge sets

Type hints (def total(prices: list[float]) -> float) are not enforced at runtime — they exist for your editor, for type checkers, and later for libraries like Pydantic and FastAPI that read and do enforce them.

A comprehension builds a collection in one expression: [expression for item in iterable if condition]. Read it left to right — "give me `expression` for each `item` in `iterable`, where `condition` is true."

[n * n for n in nums if n % 2 == 0]      # list comprehension
{w: len(w) for w in words}                # dict comprehension
{w.lower() for w in words}                # set comprehension

Exercise

Write six small functions: square the even numbers in a list, map words to their lengths, dedupe+lowercase+sort a list of strings, invert a dict, return the first item of a list or None, and group words by length.

Check yourself

1. When would you pick a set over a list? Give one example.

2. If a function is hinted def f(x: int) and you call f("hi"), what happens, and why?

← Previous lesson

Toolchain: uv, virtual environments, project layout

Answer the check-yourself questions to unlock this