Built-in Collections and Comprehensions
Know the cost of each operation on lists, dicts, sets and deques, how slicing and sorting really behave, and the collections and itertools tools interviewers expect you to reach for.
Key points
- 1
Lists are dynamic arrays: append and pop at the end are O(1), but insert(0), pop(0) and
x in lstare O(n). Usedequefor queues andsetfor membership. - 2
Slices clamp their bounds and never raise; plain slice assignment can resize the list, while extended slices (with a step) need the same number of items.
- 3
sorted()returns a new list andlist.sort()returns None. Sorts are stable, so multi-key sorts can be done with a tuple key or with successive sorts from the least significant key. - 4
Dicts keep insertion order (guaranteed since 3.7).
keys(),values()anditems()are live views, and key views support set operations.d1 | d2(3.9) merges with right-hand values winning. - 5
defaultdictinserts on anyd[key]read;Counterreturns 0 for missing keys without inserting, and its arithmetic operators drop non-positive counts. - 6
itertools.groupbyonly groups consecutive equal keys, so sort with the same key first; group iterators are shared and are emptied when groupby advances. - 7
heapq is a min-heap on a plain list: heapify first, and add a counter as a tie-breaker when payloads are not comparable.
Common traps
str.strip,lstripandrstripremove a set of characters, not a substring:'https://shop.com'.lstrip('https://')is'op.com'. Useremoveprefix/removesuffix.[[0] * 3] * 3repeats the same inner list three times; build grids with a comprehension.Removing items from a list while looping over it skips elements; adding keys to a dict while iterating over it raises RuntimeError.
Read the source
Test yourself on Built-in Collections and Comprehensions
Ten questions, with the answer and explanation after each one.