Skip to content
Streak:0Loading your progress…Sign in

Module 2 · Lesson 2 of 2

Comprehensions & generators

map/filter in one readable line, and lazy evaluation. ~20 min

Lesson notes

Coming from TypeScript

TypeScript

const squares = nums.filter(n => n % 2 === 0).map(n => n * n);
const byId = Object.fromEntries(users.map(u => [u.id, u]));

Python

squares = [n * n for n in nums if n % 2 == 0]
by_id = {u["id"]: u for u in users}
unique_domains = {email.split("@")[1] for email in emails}

Swap the brackets for parentheses and you get a generator expression — it produces values lazily. sum(x * x for x in range(10_000_000)) never builds a 10M-element list. Generators are central to streaming LLM responses and processing large datasets.

Sorting with key functions
users = [{"name": "b", "age": 30}, {"name": "a", "age": 25}]
sorted(users, key=lambda u: u["age"])               # by age
sorted(users, key=lambda u: (-u["age"], u["name"]))  # age desc, then name
collections: the standard library's power tools
from collections import Counter, defaultdict
Counter("mississippi").most_common(2)   # [('i', 4), ('s', 4)]
groups = defaultdict(list)
for word in ["apple", "avocado", "banana"]:
    groups[word[0]].append(word)        # no KeyError on first access

Practice

  1. 1. Group words by length

    easy10 XP

    Write group_by_length(words) returning a dict mapping each length to a sorted list of words of that length.

    Ctrl/⌘ + Enter runs the tests · Esc then Tab leaves the editor

  2. 2. Top-k frequent words

    medium25 XP

    Write top_k(text, k) returning the k most common lowercase words in text as a list of (word, count) tuples, sorted by count desc then word asc. Words are split on whitespace; strip .,!? from each word.

    Ctrl/⌘ + Enter runs the tests · Esc then Tab leaves the editor