Skip to the page

Performance and memory · core

Choosing a data structure, and vectorising loops

The right built-in structure often turns a slow program into a fast one: a set for lookups, a deque for queues, a heap for top N, a Counter for counting. For big numeric data, vectorised operations beat Python loops.

The notes

What you must know

  • A set has average O(1) lookup. x in list is O(n), so a loop over 50 lakh ids with a list becomes quadratic.
  • collections.deque: append and popleft are O(1); list.pop(0) is O(n). Between threads use queue.Queue.
  • Top N from a stream: heapq with a min-heap of size N, or heapq.nlargest(N, stream).
  • Counting: collections.Counter and most_common(); grouping: defaultdict(list). bisect for sorted lists; tuples for fixed records; array or NumPy for millions of numbers.
  • Dicts are hash tables that keep insertion order (guaranteed since 3.7). Many equal hashes slow lookups.
  • If data is too big for memory: use the database, sort and stream, or a Bloom filter.
  • A reconciliation script that matches payments to bank lines: replace "in list" and nested loops with a dict keyed by UTR and a set of matched ids, giving O(n). Replace one INSERT and commit per row with executemany or COPY in batches.
  • A Python loop pays interpreter overhead and creates a Python object per value. iterrows also builds a Series per row. Vectorised operations (column arithmetic, boolean masks, np.where, np.select, Series.map with a dict, pd.cut) run the loop in C. apply(axis=1) still calls Python per row. Check the new result against the old on a sample.

The red pen

Common traps: mistake → fix

  • Mistake: list is fine as a queue

    Fix: pop(0) is O(n); use deque.

  • Mistake: apply is vectorised

    Fix: apply(axis=1) calls a Python function for every row.

  • Mistake: Use multiprocessing around an O(n squared) loop

    Fix: fix the algorithm first.

  • Mistake: A bigger server fixes slow nightly jobs

    Fix: worse-than-linear code grows faster than hardware.

Easy to hard

Questions interviewers ask, easy to hard

  1. Which structure would you use to check if an id was seen among 50 lakh ids?
  2. How do you keep the 10 biggest orders from a stream?
  3. Why is list.pop(0) a bad queue?
  4. A pandas loop with iterrows takes 40 minutes for two crore rows. What do you change?
  5. A reconciliation job went from 4 minutes to 7 hours when volume grew 30 times. Why?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview