Python25 min readBeginner

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.

🚂
Real-life analogy — Each one is a different shape
A LIST is a train of cars in a fixed order. A DICT is a coat-check counter — give them a ticket (key), get back your coat (value). A SET is the bouncer's clipboard — they only care if your name is on it. A TUPLE is a sealed envelope — once mailed, the contents can't change.

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.

Array operations
Watch how the underlying memory shifts on each operation.
0
3
1
1
2
4
Start with a list [3, 1, 4]
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.

Watch a dict actually store keys
Each key is hashed to a bucket index. Two keys in the same bucket → "collision", resolved by chaining.
Hash function
hash("Ada")
= 65662
% 8
→ bucket 6
0
empty
1
empty
2
empty
3
empty
4
empty
5
empty
6
Ada: 36
7
empty
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)
💡 Tip
Whenever you find yourself looping through a list to find something by name or id, you almost certainly want a dict instead.

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
Which collection lets you ask 'is X in this group' in O(1) average time AND keeps duplicates out?