MrFaws Docs
Learn Python

Data Structures

Choose the right collection and understand its performance.

TypeOrderedMutableBest for
listYesYesAn ordered collection
tupleYesNoFixed values and coordinates
setNoYesUnique values and fast membership tests
dictYesYesKeys mapped to values

Stacks and queues

from collections import deque

stack = []
stack.append("job-1")
current = stack.pop()

queue = deque(["job-1", "job-2"])
queue.append("job-3")
current = queue.popleft()

Use a list as a stack and deque as a queue. Removing the first item from a regular list requires shifting every remaining item.

Useful collection tools

from collections import Counter, defaultdict
import heapq

counts = Counter("mississippi")
groups = defaultdict(list)
groups["admin"].append("Ada")

jobs = [(20, "backup"), (5, "alert"), (10, "email")]
heapq.heapify(jobs)
priority, job = heapq.heappop(jobs)

Dictionary and set lookups are normally O(1), list searches are O(n), and efficient sorting is O(n log n).

Exercise

Build a priority job queue. Prevent duplicate IDs with a set, keep job details in a dictionary, and select the next job with a heap.

On this page