Python by Contrast
The data model — lists, dicts & dunders
Lesson 3 of 5
What you'll learn
- Map list, dict, tuple and set onto their JS equivalents
- Replace map/filter chains with comprehensions
- See how dataclasses and dunder methods power the object protocol
Python's four core containers line up with JS almost one to one: a list is an Array, a dict is a Map (insertion-ordered, any hashable key) that you use as casually as an object literal, a tuple is a fixed-length immutable sequence like a readonly tuple type, and a set is a Set — but with real operators.
nums = [1, 2, 3]
user = {"name": "Ada", "age": 36}
point = (2, 5) # immutable; unpacks: x, y = point
tags = {"py", "ts"} | {"go"} # set union with an operator
Comprehensions instead of map/filter
Where TS chains array methods, Python has a dedicated syntax — expression first, then the loop, then the condition:
squares = [n * n for n in nums if n % 2 == 0]
ages = {u["name"]: u["age"] for u in users} # dict comprehension
const squares = nums.filter((n) => n % 2 === 0).map((n) => n * n);
const ages = Object.fromEntries(users.map((u) => [u.name, u.age]));
Dataclasses and dunders
Where TS pairs an interface with object literals, Python's dataclass generates the constructor, repr, and equality from annotated fields — and dunder methods (double-underscore, like __add__) let your type plug into the language's operators:
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
def __add__(self, other: "Point") -> "Point":
return Point(self.x + other.x, self.y + other.y)
print(Point(1, 2) + Point(3, 4)) # Point(x=4, y=6)
Everything "built in" routes through dunders: len(x) calls __len__, a for loop calls __iter__, + calls __add__, print calls __str__. JS has exactly one comparable hook — Symbol.iterator — while Python makes the whole language pluggable this way.
Protocols, not keywords
There is no implements and no operator-overloading keyword. Define the right dunder and your type behaves like a built-in; this is the same structural spirit as TS, applied to behavior.
The challenge is a JS model of two comprehensions mapped to array methods, plus Symbol.iterator — JS's one true dunder.
Run it. This maps list and dict comprehensions onto filter/map, then models __iter__ with Symbol.iterator.
What lets a custom Python object respond to len(), for loops and the + operator?
Next: async def and await will look familiar — but you start the event loop yourself.
Saved on this device. Sign in to sync your progress everywhere.