Lesson 14 / 47

Comprehensions & Nested Data

Build lists, dicts and sets in one line, and combine collections.

List comprehension

List comprehensions build a new list from an iterable, optionally filtered by if.

squares = [n * n for n in range(6)]
evens = [n for n in range(20) if n % 2 == 0]
print(squares)
print(evens)

Dict & set comprehension

The same idea works for dicts and sets — just change the brackets.

squares = {n: n * n for n in range(5)}
unique_lens = {len(w) for w in ["hi", "bye", "ok"]}
print(squares)
print(unique_lens)

Nested data structures

Lists and dicts can nest: a list of dicts (records), or a dict of lists (grouped data) — very common in real programs.

Quick check: What does `[n for n in range(5) if n % 2 == 0]` produce?

  • [1, 3]
  • [0, 2, 4]
  • [0, 1, 2, 3, 4]
Answer

[0, 2, 4] — Only even numbers from 0-4 pass the `if` filter.