Skip to content

Data structures

First PublishedLast UpdatedByAtif Alam
xs = [1, 2, 3] # list — ordered, mutable (dynamic array)
t = (1, 2) # tuple — ordered, immutable
d = {"a": 1, "b": 2} # dict — key–value; insertion order preserved (3.7+)
s = {1, 2, 3} # set — unordered, unique, hashable elements only
f = frozenset({1, 2}) # frozenset — immutable set
name = "hello" # str — immutable character sequence
b = b"bytes" # bytes — immutable; bytearray — mutable

Empty: [] list, {} dict, set() set (not {} — that’s a dict).

Use caseStructure
Ordered sequence you need to changelist (append, insert, remove) — default for “a sequence of things”
Ordered sequence that shouldn’t changetuple (return values, dict keys, coordinates)
Look up by keydict (names → values, id → record)
Unique items or fast “is x in here?”set (order doesn’t matter, no duplicates)
Queue or stack from both endsdeque (use instead of list when you pop from the front often, e.g. BFS)
Smallest item, priority queue, “top K”heapq (min-heap)

Lists are ordered and mutable. Typical operations:

fruits = ["apple", "banana", "cherry"]
# Create — add elements
fruits.append("mango") # end
fruits.insert(1, "blueberry") # at index 1
print("After Create:", fruits)
# Read — index or iterate
print("Index 0:", fruits[0])
print("All fruits:", fruits)
# Update — assign by index
fruits[3] = "grape"
print("After Update:", fruits)
# Delete — by value or by index
fruits.remove("banana") # first matching value
popped = fruits.pop(0) # index; returns the item
print("After Delete:", fruits)
print("Popped item:", popped)

Example output:

After Create: ['apple', 'blueberry', 'banana', 'cherry', 'mango']
Index 0: apple
All fruits: ['apple', 'blueberry', 'banana', 'cherry', 'mango']
After Update: ['apple', 'blueberry', 'banana', 'grape', 'mango']
After Delete: ['blueberry', 'grape', 'mango']
Popped item: apple

Key points: remove(x) drops the first x and errors if missing. pop(i) removes the item at i and returns it; pop() removes the last item.

Dicts map keys to values. Keys must be hashable (e.g. str, int, tuple of immutables).

employee = {"name": "Alex", "role": "SRE", "level": "Senior"}
# Create — new key
employee["company"] = "ExampleCorp"
print("After Create:", employee)
# Read — subscript or .get() for a default
print("Name:", employee["name"])
print("Dept:", employee.get("department", "N/A"))
# Update — reassign key
employee["level"] = "Staff"
print("After Update:", employee)
# Delete — del or .pop()
del employee["company"]
removed = employee.pop("level", None)
print("After Delete:", employee)
print("Removed value:", removed)
print("\nKey-Value pairs:")
for key, value in employee.items():
print(f" {key}: {value}")

Example output:

After Create: {'name': 'Alex', 'role': 'SRE', 'level': 'Senior', 'company': 'ExampleCorp'}
Name: Alex
Dept: N/A
After Update: {'name': 'Alex', 'role': 'SRE', 'level': 'Staff', 'company': 'ExampleCorp'}
After Delete: {'name': 'Alex', 'role': 'SRE'}
Removed value: Staff
Key-Value pairs:
name: Alex
role: SRE

Key points: d[key] raises KeyError if key is missing; d.get(key, default) does not. d.pop(key, default) returns default when the key is absent.

For patterns on lists of dictionaries (filtering, grouping, aggregations), see Records and iteration.

The rule you’ll hit first: You cannot use a list as a dict key or put a list inside a set. If you need something list-like in those places, use a tuple instead.

Why? Dict keys and set members must be hashable. Hashable means Python can turn the value into a stable number (a hash) and use that number to find the key or check membership quickly. If the value could change later (like a list), the hash would no longer match, so Python only allows values that don’t change — i.e. immutable types like tuple, str, or numbers. A list can change (append, remove), so it isn’t hashable; a tuple can’t change, so it is.

Mutable = you can change it after creation (e.g. append to a list, add to a dict). Immutable = you cannot change it; you’d create a new value instead (e.g. tuple, string, numbers).

Mutable types: list, dict, set. Immutable types: tuple, str, frozenset, int, float.

  • collections: deque (double-ended queue), defaultdict, Counter, OrderedDict, namedtuple
  • heapq: min-heap on a list
  • queue: Queue, LifoQueue, PriorityQueue (thread-safe)
  • array: typed arrays

Third-party: NumPy, Pandas, and graph/tree libs for specialized needs.

These structures are the base you’ll use when learning algorithms:

  • list — dynamic array (indexing, sorting, DP)
  • dict — O(1) lookup and graph adjacency
  • set — visited sets and uniqueness
  • tuple — immutable pairs (edges, coords)
  • deque — BFS and queues
  • heapq — Dijkstra and heaps

See the Algorithms section for more.