Python for Polyglots
Lesson 3 · Data

list, tuple, dict, set

Python has four built-in collections, each with literal syntax.

PythonJavaTS / JSPHP
list [1, 2]
ordered, mutable
ArrayList<T>Arrayindexed 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 / LinkedHashMapMap or {}associative array
set {1, 2}
unique, unordered
HashSetSet— 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].

Using a dictionary
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))
All four in action
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)
Quiz: What does this print?
grid = [[]] * 3
grid[0].append("x")
print(grid)
Exercise 13: Count words

Count the words in text, ignoring case and splitting on whitespace.

word_count("the cat The hat") → {"the": 2, "cat": 1, "hat": 1}

Exercise 14: Group by length

Group words by their length.

group_by_length(["hi", "yo", "cat"]) → {2: ["hi", "yo"], 3: ["cat"]}

Exercise 15: Items in both lists

Return the items that appear in both lists, sorted, with no duplicates.

common_items([3, 1, 2, 2], [2, 3, 4]) → [2, 3]

Exercise 16: Dedupe, keep order

Remove duplicates but keep the order in which items first appear.

dedupe_keep_order([3, 1, 3, 2, 1]) → [3, 1, 2]

Exercise 17: Invert a dict

Swap keys and values.

invert_dict({"a": 1, "b": 2}) → {1: "a", 2: "b"}