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

Module 2 · Lesson 1 of 2

Lists, dicts, sets, tuples

The four collections you'll use every day, with their costs. ~20 min

Lesson notes

Coming from TypeScript

TypeScript

const nums: number[] = [3, 1, 2];
const ages: Record<string, number> = { ada: 36 };
const seen = new Set<string>();
const point: [number, number] = [1, 2];

Python

nums: list[int] = [3, 1, 2]
ages: dict[str, int] = {"ada": 36}
seen: set[str] = set()      # {} is an empty dict!
point: tuple[int, int] = (1, 2)

Costs to remember: list index/append is O(1), x in list is O(n). x in dict / x in set is O(1) on average — that's why converting a list to a set is the first move in many interview problems. Tuples are immutable and hashable, so they can be dict keys.

Slicing works on lists, tuples and strings
xs = [0, 1, 2, 3, 4, 5]
xs[1:4]    # [1, 2, 3]
xs[:2]     # [0, 1]
xs[-2:]    # [4, 5]
xs[::-1]   # reversed copy
"python"[::2]  # 'pto'
Dict essentials
user = {"name": "Ada", "langs": ["py"]}
user.get("email")            # None instead of KeyError
user.get("email", "n/a")     # with default
for key, value in user.items():
    ...
merged = {**user, "role": "admin"}   # like JS spread

Practice

  1. 1. Dedupe, keep order

    easy10 XP

    Write dedupe(items) returning a new list with duplicates removed, keeping the first occurrence order. Must be O(n).

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

  2. 2. Empty braces

    Quizeasy5 XP
    What is type({})?