Python built-ins and their costs
Pick the right built-in container for a task knowing the complexity of its operations.
By Invicly Tech, , in Data Structures & Algorithms. About 9 minutes to read.
In short
Python's built-in containers are already well-tuned data structures, but each operation has a cost you must know. Lists are dynamic arrays, dicts and sets are hash tables, deque is a double-ended queue, and heapq and bisect add heaps and binary search over lists. Choosing the wrong one silently turns O(n) into O(n^2).
Explained simply
Python gives you ready-made data structures. A list is a growable row of boxes. A dict is a labelled cabinet where you find things by name. A set is a bag that only cares whether something is inside. Picking the right one is often the whole trick to a fast solution.
Each one is quick at some jobs and slow at others. Finding the 5th item in a list is instant, but checking if a value is somewhere in a list means looking through every box. A set answers "is it in here?" almost instantly, but it has no order and no positions.
The collections module adds handy tools. deque is a line of people where you can join or leave at either end quickly. Counter counts things for you. defaultdict creates an empty value the first time you use a key, so you skip the "if key not in dict" dance.
Two more modules round out the kit. heapq keeps the smallest item ready to grab, like a to-do list sorted by urgency. bisect finds where a value belongs in a sorted list using binary search. Together these cover almost every structure you need in coding problems.
Press Play on a diagram to walk through it one step at a time.
- Index and append: O(1)
- insert(0) and pop(0): O(n)
- x in list: O(n)
- sort: O(n log n)
- Get, set, delete: O(1) average
- x in set: O(1) average
- Keys must be hashable
- Dict keeps insertion order
- deque appendleft and popleft: O(1)
- deque index middle: O(n)
- heappush and heappop: O(log n)
- heap[0] is the minimum
- Access by position
- list
- Is x present? Look up by key
- set
- dict
- Add or remove at both ends
- collections.deque
- Always grab the smallest
- heapq on a list
- Count or group things
- Counter
- defaultdict
- Search a sorted list
- bisect
In depth
Why the list is fast at the end and slow at the front
A Python list stores pointers in one continuous block of memory. Reading xs[i] is one calculation: start address plus i times the pointer size. That is O(1).
Appending to the end usually just fills the next free slot. But inserting or removing at the front means every other element must shift one place, which is O(n). That is why xs.pop(0) in a loop of n items costs O(n^2) overall, and why queues should use deque.
- xs[i], xs[i] = v, append, pop(): O(1)
- insert(0, v), pop(0), remove(v): O(n)
- v in xs, xs.index(v), min, max: O(n)
- xs.sort(): O(n log n)
- xs[a:b] copies: O(b - a)
Dicts and sets: hashing behind the scenes
Dicts and sets are hash tables. When you look up a key, Python computes a number from it (its hash), jumps to a slot, and checks the few items there. That is O(1) on average, no matter how big the dict.
Keys must be hashable, meaning they cannot change. Strings, numbers and tuples work. Lists and dicts do not, so convert a list to a tuple to use it as a key. Since Python 3.7, dicts remember insertion order, which is handy for output.
- 1d["apple"]
Look up a key
- 2hash("apple")
Turn the key into a number
- 3Jump to a slot
Slot index comes from the hash
- 4Compare keys
Check the few entries found there
- 5Return value
O(1) on average
Counter and defaultdict save lines and bugs
Counter("banana") gives counts for each letter in one call, and most_common(k) returns the top k. Two Counters can be compared with == to check if two words are anagrams.
defaultdict(list) gives you an empty list the first time you touch a new key. Grouping becomes one line: groups[key].append(item). defaultdict(int) starts counts at zero. Both are still plain dicts, with the same O(1) average costs.
heapq and bisect in one minute
heapq turns a plain list into a min-heap. heappush and heappop cost O(log n), and h[0] is always the smallest item. For a max-heap, push negative numbers. heapify turns an existing list into a heap in O(n).
bisect works on a list that is already sorted. bisect_left(xs, v) returns the first index where v could go, in O(log n). insort inserts and keeps the list sorted, but the insert itself still shifts items, so it is O(n).
- heapq.nlargest(k, xs) is O(n log k)
- Push tuples like (priority, item) to sort by priority
- bisect_left: first index with xs[i] >= v
- bisect_right: first index with xs[i] > v
Learn it in 4 short steps
About 40m each. Track them with a timer in your plan.
- 1Review list, dict and set operation costs~40m
- 2Use deque, Counter and defaultdict~40m
- 3Use heapq and bisect modules~40m
- 4Write quick tests with pytest~40m
Key points
- Use a set, not a list, for repeated membership tests.
- Use collections.deque for queues; list.pop(0) is O(n).
- Counter and defaultdict remove boilerplate for counting and grouping.
- heapq is a min-heap; push negated values for a max-heap.
Key terms
Tap a card to flip it. 0/4 known
Examples
from collections import Counter, defaultdict, deque
import heapq, bisect
print(Counter('banana').most_common(1)) # [('a', 3)]
groups = defaultdict(list)
for w in ['eat', 'tea', 'tan']:
groups[''.join(sorted(w))].append(w)
q = deque([1, 2]); q.appendleft(0); q.popleft()
h = [5, 1, 3]; heapq.heapify(h); print(heapq.heappop(h)) # 1
print(bisect.bisect_left([1, 3, 5], 4)) # 2Same task, 1,000 times faster
We check 10,000 lookups against 10,000 numbers. With a list, each "in" scans up to 10,000 items, so up to 100 million comparisons. With a set, each "in" is one hash and a jump. The only change is wrapping the data in set(). On a typical laptop the list version takes around a second; the set version takes about a millisecond.
import timeit
nums = list(range(10_000))
queries = list(range(5_000, 15_000))
num_set = set(nums)
slow = timeit.timeit(lambda: sum(q in nums for q in queries), number=1)
fast = timeit.timeit(lambda: sum(q in num_set for q in queries), number=1)
print(f"list: {slow:.3f}s set: {fast:.5f}s")A word-count tool with Counter and defaultdict
Given a sentence, find the most common word and group words by their first letter. Counter does the counting in one line. defaultdict(list) builds the groups without checking whether each key exists. For "the cat and the hat", "the" appears twice, and the letter t group holds "the", "the".
from collections import Counter, defaultdict
words = "the cat and the hat".split()
print(Counter(words).most_common(1)) # [('the', 2)]
by_letter = defaultdict(list)
for w in words:
by_letter[w[0]].append(w)
print(dict(by_letter))
# {'t': ['the', 'the'], 'c': ['cat'], 'a': ['and'], 'h': ['hat']}Quick reference
- list: index and append O(1); insert(0)/pop(0) and x in list O(n)
- dict/set: get, add, delete, x in s are O(1) average
- deque: append, appendleft, pop, popleft all O(1)
- heapq: push/pop O(log n), h[0] is the min, heapify O(n)
- bisect_left on a sorted list: O(log n)
- Max-heap trick: push -x, negate again when popping
- Use tuples, not lists, as dict keys
- sorted(xs, key=...) is stable and O(n log n)
Common mistakes
- Using a list as a queue with pop(0) in BFS.
- Using lists as dict keys; convert them to tuples first.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write first_unique(s) that returns the index of the first character that appears exactly once in s, or -1. Example: "leetcode" returns 0, "aabb" returns -1.
- Exercise 2medium
Write k_smallest(xs, k) that returns the k smallest numbers in sorted order using heapq, without sorting the whole list. Example: [7, 2, 9, 4, 1], k = 3 returns [1, 2, 4].
- Exercise 3hard
Write count_in_range(xs, queries) where xs is a list of numbers and each query is (lo, hi). Return how many numbers fall in [lo, hi] for each query, fast enough for 10^5 numbers and 10^5 queries. Example: xs = [5, 1, 8, 3, 9], queries [(2, 8), (10, 20)] returns [3, 0].
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is a Python list a linked list or an array?
- An array of pointers that grows automatically. That is why indexing is fast and inserting at the front is slow.
- Why does heapq not have a max-heap?
- It only implements a min-heap. Push negated numbers, or tuples like (-priority, item), to get max-heap behaviour.
- When should I use OrderedDict now that dicts keep order?
- Rarely. It still helps when you need move_to_end or popitem(last=False), for example when building an LRU cache.
- Is set lookup always O(1)?
- On average, yes. In theory many keys with the same hash could make it O(n), but with built-in types this almost never happens in practice.