Lists, Dicts, Sets, Tuples
The four built-in collections — what they are, when to use which, and how they compare.
Why four?
Almost every program needs to store and manipulate groups of values. Python ships with four general-purpose collections, each tuned for different access patterns. Picking the right one is one of the highest-leverage decisions you make as a programmer — the wrong choice can make code 1000x slower.
Lists
A list is an ordered, mutable sequence of values. "Ordered" means items keep the position you put them in. "Mutable" means you can change them after creation. Lists use square brackets.
nums = [3, 1, 4, 1, 5, 9, 2, 6]
# Access by index (zero-based)
print(nums[0]) # 3
print(nums[-1]) # 6 (negative indexes count from the end)
# Slicing: nums[start:stop]
print(nums[1:4]) # [1, 4, 1]
# Common operations
nums.append(5) # add to end
nums.insert(0, 99) # insert at index 0
nums.remove(1) # remove the first occurrence of 1
nums.sort() # sort in place
print(nums)- Best for: ordered collections you need to iterate over or modify by index.
- Append at end: O(1).
- Insert/remove at arbitrary position: O(n).
- Lookup by index: O(1).
Dicts (dictionaries)
A dict is a collection of key-value pairs. You don't access items by position — you access them by key. Internally, dicts are hash tables, which means lookups are blazing fast (O(1) on average). Since Python 3.7, dicts also preserve insertion order.
user = {"name": "Ada", "age": 36, "role": "engineer"}
print(user["name"]) # Ada
print(user.get("missing", "n/a")) # safer — returns default if missing
user["email"] = "ada@example.com" # add or update
del user["age"] # remove
# Iterate
for key, value in user.items():
print(key, "->", value)
# Check membership (fast: O(1))
print("name" in user)Sets
A set is an unordered collection of UNIQUE values. Like dicts, sets are backed by a hash table, so membership checks (`x in s`) are O(1) on average. Use a set whenever the question is "have I seen this before?" or "what items are in both A and B?".
seen = set()
seen.add("apple")
seen.add("apple") # ignored — already there
seen.add("banana")
print("apple" in seen) # True (super fast)
print(len(seen)) # 2
# Set operations
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a & b) # intersection: {3, 4}
print(a | b) # union: {1, 2, 3, 4, 5, 6}
print(a - b) # difference: {1, 2}Tuples
A tuple is like a list, but immutable — once you create it, you can't change it. Use tuples for fixed-size groups of values that belong together (a coordinate, an RGB color, a database row). Because they're immutable, tuples can be used as dict keys; lists can't.
point = (3, 4)
x, y = point # tuple unpacking
print(x, y)
# Tuples as dict keys
distances = {(0, 0): 0.0, (3, 4): 5.0}
print(distances[(3, 4)])Choosing the right collection
- Need order and may modify? → list
- Need to look things up by name/id? → dict
- Just need to know if something exists, no duplicates? → set
- Fixed-size group of related values, won't change? → tuple