Python data structures

Python data structures

Python includes flexible built-in containers and adds specialized types in collections, array, and heapq.

Help-desk ticket system

Use a dict for ticket IDs, a set for processed events, a deque for arrival order, and heapq for urgent work.

from collections import deque
import heapq

tickets_by_id = {}
processed_events = set()
waiting_tickets = deque()
urgent_tickets = []

ticket = {"id": "HD-1042", "title": "Cannot sign in", "priority": 1}
tickets_by_id[ticket["id"]] = ticket

if "evt-8" not in processed_events:
    processed_events.add("evt-8")
    waiting_tickets.append(ticket["id"])
    heapq.heappush(urgent_tickets, (ticket["priority"], ticket["id"]))

heapq removes the smallest tuple first, so 1 represents the most urgent priority here. See Data structure decisions for the reasoning and Big O notation for the cost of each operation.

Lists and tuples

list is mutable and ordered; tuple is ordered and immutable.

names = ["Ada", "Grace"]
names.append("Linus")

point = (10, 20)

Dictionaries

dict maps unique keys to values and preserves insertion order.

stock = {"apples": 12}
stock["apples"] += 1

Sets and frozensets

set stores unique values; frozenset is its immutable counterpart.

tags = {"python", "web"}
tags.add("python")  # Duplicate ignored.

permissions = frozenset({"read", "write"})

Queues and stacks with deque

collections.deque efficiently adds and removes from either end.

from collections import deque

queue = deque(["first"])
queue.append("second")
first = queue.popleft()

stack = deque()
stack.append("last")
last = stack.pop()

Priority queues with heapq

heapq provides a min-heap: the smallest priority is removed first.

import heapq

jobs = []
heapq.heappush(jobs, (1, "critical"))
heapq.heappush(jobs, (5, "documentation"))
priority, job = heapq.heappop(jobs)

Counting and grouping

Counter counts hashable values and defaultdict supplies default values for missing keys.

from collections import Counter, defaultdict

counts = Counter("banana")
groups = defaultdict(list)
groups["fruit"].append("apple")

Compact numeric data

Use array for homogeneous primitive values and bytearray for mutable bytes.

from array import array

scores = array("i", [10, 20, 30])
buffer = bytearray(b"abc")
buffer[0] = ord("A")

Custom linked nodes

Python does not include a linked-list type; define nodes when linked semantics are required.

from dataclasses import dataclass

@dataclass
class Node:
    value: int
    next: "Node | None" = None

head = Node(1, Node(2))

See Data structures for shared concepts and examples across languages.