Collections
Collections: the Python data structures you will use every day
Section titled “Collections: the Python data structures you will use every day”Python ships four built-in collection types: list, tuple, dict, and set. As a TypeScript developer you already have mental models for all of them — the mapping is close, but each Python type has a distinct flavour.
| Python | TypeScript | Key difference |
|---|---|---|
list | Array | Mutable, ordered |
tuple | Readonly array / [T, U] | Immutable, fixed-length |
dict | Record<K,V> / object / Map | Mutable key-value |
set | Set | Unique unordered values |
list — Python’s Array
Section titled “list — Python’s Array”// TypeScript Arrayconst nums: number[] = [1, 2, 3, 4, 5];
nums.push(6);nums.splice(0, 1); // remove first element
console.log(nums[0]); // 2console.log(nums.length); // 5
const doubled = nums.map((n) => n * 2);const evens = nums.filter((n) => n % 2 === 0);# Python listnums: list[int] = [1, 2, 3, 4, 5]
nums.append(6) # pushnums.pop(0) # remove first element
print(nums[0]) # 2print(len(nums)) # 5
doubled = [n * 2 for n in nums] # list comprehensionevens = [n for n in nums if n % 2 == 0]List comprehensions ([expr for x in iterable if condition]) are idiomatic Python — prefer them over map/filter for simple transformations.
dict — Python’s Record / Map
Section titled “dict — Python’s Record / Map”// TypeScript object / Recordconst user: Record<string, unknown> = { name: "Alice", age: 30,};
user["role"] = "admin"; // add keydelete user["age"]; // remove key
console.log(user["name"]); // Aliceconsole.log(user["missing"] ?? "n/a"); // n/a (nullish coalescing)
for (const [k, v] of Object.entries(user)) { console.log(k, v);}# Python dictuser: dict[str, object] = { "name": "Alice", "age": 30,}
user["role"] = "admin" # add keydel user["age"] # remove key
print(user["name"]) # Aliceprint(user.get("missing", "n/a")) # n/a (safe lookup)
for key, value in user.items(): print(key, value)Use .get(key, default) instead of dict[key] when the key might be absent — it returns the default instead of raising a KeyError.
set — unique values
Section titled “set — unique values”// TypeScript Setconst tags = new Set<string>(["python", "web", "python"]);tags.add("api");
console.log(tags.has("python")); // trueconsole.log(tags.size); // 3tags.delete("web");# Python set — literal syntax with {}tags: set[str] = {"python", "web", "python"} # duplicate removedtags.add("api")
print("python" in tags) # Trueprint(len(tags)) # 3tags.discard("web") # remove without error if absentSlicing — Python’s killer feature for sequences
Section titled “Slicing — Python’s killer feature for sequences”Python slicing lets you extract sub-sequences with [start:stop:step]. There is no direct TypeScript equivalent — .slice() exists on arrays but lacks the step parameter and negative indexing is not supported natively.
// TypeScriptconst nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(nums.slice(2, 5)); // [2, 3, 4]console.log(nums.slice(-3)); // [7, 8, 9]// No step parameter in .slice()# Python slicing — works on list, tuple, and strnums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(nums[2:5]) # [2, 3, 4] — indices 2,3,4print(nums[-3:]) # [7, 8, 9] — last 3print(nums[::-1]) # reversed — step of -1print(nums[::2]) # [0,2,4,6,8] — every otherprint(nums[1:8:2]) # [1,3,5,7] — start:stop:step
# Strings too!s = "Hello, World!"print(s[:5]) # Helloprint(s[-6:]) # World!Try it
Section titled “Try it”# listnums = [1, 2, 3, 4, 5]print(nums[1:4]) # [2, 3, 4]print(nums[::-1]) # reversednums.append(6)print(nums)
# list comprehensiondoubled = [n * 2 for n in nums]print(doubled)
# tuple (immutable)point = (10, 20)x, y = pointprint(f"x={x}, y={y}")
# dictuser = {"name": "Alice", "age": 30}user["role"] = "admin"print(user.get("name"))print(user.get("missing", "default"))for k, v in user.items(): print(f" {k}: {v}")
# settags = {"python", "web", "python"}tags.add("api")print(tags)print("python" in tags)Loading Python runtime (first run only)…