list, tuple, dict, set
Python has four built-in collections, each with literal syntax.
| Python | Java | TS / JS | PHP |
|---|---|---|---|
list [1, 2]ordered, mutable | ArrayList<T> | Array | indexed array |
tuple (1, "a")ordered, immutable, hashable | record / List.of() | TS [number, string] (compile-time only) | — just an array |
dict {"a": 1}key → value, insertion-ordered | HashMap / LinkedHashMap | Map or {} | associative array |
set {1, 2}unique, unordered | HashSet | Set | — array keys / array_unique |
Watch out: {} is an empty dict. An empty set is written set().
Tuples are immutable, which makes them hashable. That means a tuple can be a dict key, like {(0, 0): "origin"}. JS Map can't do this by value, because [0,0] !== [0,0].
ages = {"alice": 30}
ages["bob"] = 25
print(ages.get("carol", 0))
for name, age in ages.items():
print(name, age)
print("alice" in ages, len(ages))nums = [3, 1, 2]
nums.append(4)
print("list ", nums, nums[0], nums[-1])
point = (3, 4)
x, y = point
print("tuple", point, x, y)
places = {(0, 0): "origin", (3, 4): "home"}
print("dict ", places[(3, 4)], places.get((9, 9), "unknown"))
a, b = {1, 2, 3}, {2, 3, 4}
print("set ", a & b, a | b, a - b, 2 in a)grid = [[]] * 3
grid[0].append("x")
print(grid)Count the words in text, ignoring case and splitting on whitespace.
word_count("the cat The hat") → {"the": 2, "cat": 1, "hat": 1}
Group words by their length.
group_by_length(["hi", "yo", "cat"]) → {2: ["hi", "yo"], 3: ["cat"]}
Return the items that appear in both lists, sorted, with no duplicates.
common_items([3, 1, 2, 2], [2, 3, 4]) → [2, 3]
Remove duplicates but keep the order in which items first appear.
dedupe_keep_order([3, 1, 3, 2, 1]) → [3, 1, 2]
Swap keys and values.
invert_dict({"a": 1, "b": 2}) → {1: "a", 2: "b"}