Learn Python
Data Structures
Choose the right collection and understand its performance.
| Type | Ordered | Mutable | Best for |
|---|---|---|---|
list | Yes | Yes | An ordered collection |
tuple | Yes | No | Fixed values and coordinates |
set | No | Yes | Unique values and fast membership tests |
dict | Yes | Yes | Keys 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.