Vasu Patel logoVasu Patel
← Python Syntax & DSA Reference
All chapters in this track
  1. 011. Variables, Types & Operators
  2. 022. Strings
  3. 033. Lists
  4. 044. Tuples, Sets & Dicts
  5. 055. Control Flow
  6. 066. Error Handling
  7. 077. Functions & Lambdas
  8. 088. Comprehensions
  9. 099. Built-in Functions
  10. 1010. Type Hints (3.10+)
  11. 1111. Classes & Dataclasses
  12. 1212. Iterators & Generators
  13. 1313. DSA Standard Library
  14. 1414. Python 3.9–3.11 Features for DSA
  15. 1515. DSA Idioms & Gotchas
  16. 1616. Master Quick Reference

Chapter 16 of 16

16. Master Quick Reference

Data Structures

StructureWhen to useCreateKey ops
listOrdered, index-based[1,2,3]append, pop, sort
dictKey→value mapping{}d[k], d.get(k,v)
setFast membership, uniqueset()add, discard, in
tupleImmutable, hashable(a,b)unpack, as dict key
dequeQueue, double-ended bufferdeque()appendleft, popleft
defaultdictAuto-init missing keysdefaultdict(list)same as dict
CounterFrequency mapCounter(it).most_common(k), .total()
heapqPriority queue (min)[] + heappushheappush, heappop
OrderedDictLRU CacheOrderedDict().move_to_end()

Complexity

StructureAccessSearchInsertDelete
listO(1)O(1)O(n)O(n)O(1)O(1)† endO(n)O(n)
dict/setO(1)O(1)O(1)O(1)O(1)O(1)†O(1)O(1)
dequeO(n)O(n) midO(n)O(n)O(1)O(1) endsO(1)O(1) ends
heapqO(1)O(1) min—O(log⁡n)O(\log n)O(log⁡n)O(\log n)
sorted listO(1)O(1)O(log⁡n)O(\log n) bisectO(n)O(n) insortO(n)O(n)

† Amortised

Built-ins Cheat Sheet

# Sorting
sorted(it, key=f, reverse=b)   # new list
lst.sort(key=f)                 # in-place

# Iteration
enumerate(it, start=0)         # (i, v) pairs
zip(a, b, strict=False)        # paired; strict=True raises on mismatch (3.10+)
zip(*matrix)                   # transpose

# Aggregation
sum(it, start=0)
min(it, key=f) / max(it, key=f)
any(it) / all(it)

# Math
pow(b, e, mod)                 # fast modular exponentiation
divmod(a, b)                   # (quotient, remainder)
math.gcd(*args)                # 3.9+: multi-arg
math.lcm(*args)                # 3.9+: multi-arg
math.isqrt(n)                  # integer square root
math.comb(n, k)                # C(n,k) — binomial
n.bit_count()                  # count set bits — 3.10+
bin(n); oct(n); hex(n)         # base conversion, prefixed strings
int(s, base)                   # parse string in given base
format(n, '08b')               # zero-padded binary string

# Strings
"".join(lst)                   # build string from list — O(n)
s.removeprefix(p)              # 3.9+
s.removesuffix(p)              # 3.9+

# Assignment expressions
while (n := len(x)) > 0: ...   # walrus — 3.8+, assign + use in one expr

# Error handling
try:
    ...
except (KeyError, IndexError):
    ...
finally:
    ...
raise ValueError("msg") from e

# Iterators & generators
def gen(): yield x              # lazy generator function
yield from sub_gen()            # delegate to sub-generator
class It:
    def __iter__(self): return self
    def __next__(self):
        if done: raise StopIteration
        return next_value

Standard Library for DSA

ModuleImportKey items
collectionsfrom collections import …deque, defaultdict, Counter, OrderedDict
heapqimport heapqheappush, heappop, heapify, nlargest, nsmallest
bisectimport bisectbisect_left, bisect_right, insort_left; key= 3.10+
mathimport mathgcd, lcm, isqrt, comb, inf, cbrt(3.11+), exp2(3.11+)
functoolsfrom functools import …cache(3.9+), lru_cache, cmp_to_key, reduce
itertoolsfrom itertools import …accumulate, combinations, permutations, product, chain
sysimport syssetrecursionlimit, stdin.readline

Modern Python (3.9–3.11) DSA Cheat Sheet

# 3.9+
list[int]               # built-in generic hints
dict[str,int]
d1 | d2                 # dict merge
s.removeprefix("pre_")
s.removesuffix("_suf")
math.lcm(a, b, c)
math.gcd(a, b, c)
@cache                  # functools.cache

# 3.10+
int | None              # union type hint (replaces Optional[int])
n.bit_count()           # popcount
Counter(it).total()
zip(a, b, strict=True)
bisect.bisect_left(data, v, key=lambda x: x[0])
match val:
    case pattern: ...

# 3.11+
from typing import Self  # self-reference in class methods
math.cbrt(x)             # cube root
math.exp2(x)             # 2^x
# ~60% faster than 3.10 overall

End of Python 3.11+ Syntax for DSA — August 2026