Know what every line costs
In a screening round you are expected to write idiomatic Python and state its complexity. Most accidental solutions come from one innocent-looking line, such as x in some_list inside a loop or lst.pop(0) used as a queue. Learn the cost of each container operation so you choose the container before you write the loop.
| Operation | list | dict / set | collections.deque |
|---|---|---|---|
index a[i] | key lookup avg | in the middle | |
| append at the end | amortised | insert avg | |
| remove from the end | pop() | delete avg | pop() |
| insert or remove at the front | n/a | ||
membership x in c | avg | ||
slice a[i:j] | , makes a copy | n/a | n/a |
| sort | n/a | n/a |
Hash-based operations are on average; adversarial or badly hashed keys degrade them to . len is for all three. Building a string with s += piece in a loop can cost in total; collect the pieces in a list and call "".join(pieces) once.
Tuples, hashing, comprehensions and generators
- Tuples are immutable and hashable if their contents are, so they can be dictionary keys and set members:
seen.add((row, col)). Lists cannot. - Comprehensions build containers in one expression:
[p * q for p, q in fills],{sym: 0 for sym in symbols},{x % 7 for x in xs}. They are clearer and usually faster than an explicit loop withappend. - Generators produce values lazily.
sum(x * x for x in xs)never builds the list of squares, so it uses extra memory. A generator can be consumed once:
squares = (x * x for x in range(5))
print(sum(squares), sum(squares)) # 30 0
Write a generator function with yield when you want to stream records (ticks from a file, windows of a series) without holding them all in memory.
The collections module
Three classes from collections remove most boilerplate:
Counter: a dictionary of counts.Counter("mississippi").most_common(2)returns[('i', 4), ('s', 4)], and a missing key reads as0instead of raisingKeyError.defaultdict(list)ordefaultdict(int): creates the default value on first access, so grouping isgroups[key].append(item)with noif key not in groupscheck.deque: a double-ended queue withappend,appendleft,popandpopleft. Use it for BFS queues and sliding windows.deque(maxlen=3)keeps only the last three items pushed.
heapq (a min-heap on a plain list) completes the toolkit for top- and scheduling questions.
Worked example
count pairs that sum to a target
Given trade sizes [100, 200, 300, 100, 200], count the pairs of positions whose sizes sum to . Give an solution.
Show solutionHide solution
The brute force checks all pairs, which is . Instead, scan once and keep a Counter of the sizes seen so far. When size arrives, every earlier occurrence of forms a pair with it.
from collections import Counter
def count_pairs(sizes: list[int], target: int) -> int:
seen = Counter()
pairs = 0
for s in sizes:
pairs += seen[target - s] # missing keys read as 0
seen[s] += 1
return pairs
print(count_pairs([100, 200, 300, 100, 200], 300)) # 4
Trace: at the first 200 there is one earlier 100 (1 pair); 300 needs a 0 (none); the second 100 pairs with the earlier 200 (2 pairs); the second 200 pairs with both 100s (4 pairs). Updating seen after counting is what enforces and stops an element pairing with itself. Time , space .
Sorting with keys
sorted(xs, key=f) sorts by f(x), calling f once per element. Return a tuple to sort by several fields, and negate a numeric field to reverse just that field:
trades = [("b", 101.0, 3), ("a", 100.5, 1), ("c", 101.0, 2), ("d", 100.5, 5)]
# price ascending, then quantity descending
print(sorted(trades, key=lambda t: (t[1], -t[2])))
# [('d', 100.5, 5), ('a', 100.5, 1), ('b', 101.0, 3), ('c', 101.0, 2)]
Python's sort (Timsort) is stable: items with equal keys keep their input order. list.sort() sorts in place and returns None, so xs = xs.sort() is a classic bug.
Worked example
VWAP per symbol, ranked by volume
Trades arrive as (symbol, price, quantity):
trades = [("AAPL", 190.0, 100), ("MSFT", 410.0, 50), ("AAPL", 191.0, 300),
("MSFT", 409.0, 150), ("TSLA", 250.0, 200)]
Compute each symbol's volume-weighted average price and list symbols by total volume, largest first, breaking ties alphabetically.
Show solutionHide solution
VWAP is , so accumulate notional and volume per symbol in one pass with two defaultdicts, then divide.
from collections import defaultdict
notional = defaultdict(float)
volume = defaultdict(int)
for sym, px, qty in trades:
notional[sym] += px * qty
volume[sym] += qty
vwap = {s: notional[s] / volume[s] for s in notional}
ranked = sorted(volume.items(), key=lambda kv: (-kv[1], kv[0]))
print(vwap) # {'AAPL': 190.75, 'MSFT': 409.25, 'TSLA': 250.0}
print(ranked) # [('AAPL', 400), ('MSFT', 200), ('TSLA', 200)]
Check AAPL by hand: . MSFT and TSLA tie on 200 shares, and the key (-volume, symbol) puts MSFT first. The pass is and the ranking for symbols.
Pitfalls interviewers probe
Mutable default arguments are evaluated once, when the function is defined, and shared between calls:
def append_to(x, bucket=[]):
bucket.append(x)
return bucket
print(append_to(1)) # [1]
print(append_to(2)) # [1, 2] (the same list again)
The fix is bucket=None and if bucket is None: bucket = [] inside the body.
Aliasing. [[0] * 3] * 3 is three references to one row, so grid[0][0] = 1 gives [[1, 0, 0], [1, 0, 0], [1, 0, 0]]. Build rows independently: [[0] * 3 for _ in range(3)]. Likewise b = a does not copy a list; use a.copy() or a[:].
Late-binding closures. [lambda: i for i in range(3)] produces three functions that all return 2, because each looks up i when called. Bind the value with a default: lambda i=i: i.
Integers and floats.
inthas arbitrary precision:2**100is exact and integer arithmetic never overflows./always returns a float;//is floor division and%takes the sign of the divisor:-7 // 2 == -4and-7 % 2 == 1, whileint(-7 / 2) == -3truncates towards zero.rounduses round-half-to-even:round(2.5) == 2,round(3.5) == 4.0.1 + 0.2 == 0.3isFalse; compare floats withmath.iscloseor work in integer ticks.istests identity,==tests equality. Useisonly forNone.
Knowledge check
What does -7 // 2 evaluate to in Python 3?
Knowledge check
A BFS loop processes n nodes and removes each one from the front of a Python list with queue.pop(0). What is the total cost of those removals, and what is the fix?
Knowledge check
def f(x, acc=[]): acc.append(x); return len(acc). What do the calls f(5), f(6), f(7, []) return, in that order?
Key takeaways
- Lists are fast at the end and slow at the front and for membership; dicts and sets give average lookup; deques give at both ends.
- Use comprehensions for building containers and generators for streaming; a generator is consumed once.
Counter,defaultdictanddequeturn most counting, grouping and queue code into a few lines.- Sort with tuple keys and negation; Python's sort is stable and
list.sort()returnsNone. - Watch mutable defaults, aliased nested lists, late-binding closures, floor division with negatives and half-to-even rounding.
Practice problems
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).