PYTHON CHEAT SHEET
search

PYTHON CHEAT SHEET

CORE DATA TYPES

CHAPTER 01

NUMBERS

REF 1.1
int Arbitrary precision
float 64-bit double
complex 3+4j
bool Subclass of int

DSA TIP Python ints never overflow — use freely for large factorials. Use math.isclose() for float comparison.

MUTABILITY

REF 1.2

Immutable (Hashable)

int, float, str, tuple, frozenset

Mutable

list, dict, set, bytearray

Only hashable objects can be dict keys or set members.

CONVERSIONS

Int to Binary
int("1010", 2)  # → 10
Char to ASCII
ord('a')       # → 97
List to Set
set([1, 2, 2]) # → {1, 2}

TRUTHINESS RULES

# Falsy values:
None, False, 0, 0.0, "", [], (), {}, set()

# Pattern:
if not stack: # is empty
if stack:     # has items

IDENTITY (IS VS ==)

a = [1, 2]; b = [1, 2]
a == b # True (Values match)
a is b # False (References differ)

Modern DX & Stdlib (3.10-3.14)

Modern REPL (3.13+)

The standard interactive shell now features real-time syntax highlighting, multi-line editing, and history-based tab-completion by default.

Zstandard (3.14)

The addition of compression.zstd brings high-speed, modern compression directly into the standard library.

Dead Batteries Removed

Legacy modules like distutils, asynchat, and smtpd have been permanently removed. Migrate to modern alternatives like pathlib and asyncio.

LIST — DYNAMIC ARRAY

CHAPTER 02

Python's list is a dynamic array (like Java's ArrayList). It supports O(1) index access, O(1) amortized appends, but O(n) insert/delete at arbitrary positions.

CREATION & BASIC OPS

REF 2.1
lst = []                   # empty
lst = [1, 2, 3]
lst = [0] * 5             # [0,0,0,0,0]
lst = list(range(10))      # [0..9]

# 2D list — CORRECT way
grid = [[0]*cols for _ in range(rows)]

lst.append(x)              # O(1) add to end
lst.pop()                  # O(1) remove from end
lst.pop(0)                # O(n) remove from front
lst.insert(i, x)           # O(n)
lst.extend(iterable)       # O(k)

Stack (LIFO) Pattern

stack.append(x) | stack.pop() | stack[-1] (peek)

SEARCHING & SORTING

REF 2.2
x in lst                  # O(n) linear search

# Sorting — Timsort O(n log n)
lst.sort()                 # in-place
lst.sort(reverse=True)
lst.sort(key=lambda x: x[1])

# Multi-key sort:
lst.sort(key=lambda x: (x[0], -x[1]))

# sorted() returns new list
new = sorted(lst, key=len)

BINARY SEARCH

import bisect
lst = [1, 3, 5, 7, 9]

# Find insertion point
bisect.bisect_left(lst, 5)   # → 2
bisect.bisect_right(lst, 5)  # → 3

# Insert maintaining sort
bisect.insort(lst, 4)        # [1,3,4,5,7,9]

USEFUL PATTERNS

# Flatten nested list
flat = [x for row in matrix for x in row]

# Zip & Enumerate
pairs = list(zip(a, b))
for i, v in enumerate(lst): ...

# All / Any
all(x > 0 for x in lst)
any(x > 0 for x in lst)

STRING — UNICODE SEQUENCE

CHAPTER 03

COMMON METHODS

s.strip() # Trim whitespace
s.split(",") # To list
" ".join(lst) # List to string
s.startswith("prefix")
s.replace("old", "new")
s[1:4], s[::-1] # Slice/Rev

IMMUTABILITY

Strings are immutable. To modify, convert to list or use slicing.

lst = list(s)
lst[0] = 'X'
s = "".join(lst)
Modern Formatting
f"Result: {val:.2f}"

Modern String Formatting (3.12-3.14)

Enhanced f-strings (3.12+)

f-strings are now formally integrated into the grammar. They support unrestricted quote reuse, multiline expressions with comments, and deep nesting.

f"User: {data['user']}" # No need to alternate quotes

Template Strings / t-strings (3.14)

A crucial security feature enabling deferred evaluation for safe building of SQL queries and HTML templates, neutralizing injection risks.

t"SELECT * FROM users WHERE id = {user_id}"
CHAPTER 04 Broadsheet Technical Reference

DICTIONARY · HASH MAP

Python dictionaries maintain insertion order (since 3.7+). They are highly optimized Hash Maps providing average O(1) complexity for search, insertion, and deletion.

CORE OPERATIONS

Creation & Access
d = {'a': 1, 'b': 2}
d.get('key', 0)  # Safe read
d['key'] = val    # Insert/Update
del d['key']      # Delete
Iteration
for k, v in d.items():
for k in d.keys():
for v in d.values():
Modern Merging (3.9+)
merged = d1 | d2 # d2 values overwrite d1

DSA SPECIALS

defaultdict

Auto-initializes missing keys. Essential for frequency maps and graphs.

from collections import defaultdict
adj = defaultdict(list)
adj[node].append(neighbor)
Counter

High-performance counting tool. Solves anagram and frequency problems in one line.

from collections import Counter
c = Counter("aabbbcc")
return c.most_common(1)
Chapter 05

SET · HASH SET

Unordered collection of unique elements. Average O(1) membership testing. Based on the same hash table technology as dictionaries.

"Use sets for deduplication and fast membership checks (in) instead of lists."

OPERATIONS

s.add(x)       # Add element
s.remove(x)    # Error if missing
s.discard(x)   # Safe removal
x in s         # O(1) Lookup

# Set Logic
a | b # Union
a & b # Intersection
a - b # Difference
a ^ b # Symmetric Diff

DSA PATTERNS

Cycle Detection
seen = set()
if node in seen: return True
seen.add(node)
Deduplication
unique = list(set(items))
Chapter 06 Linear Structures

DEQUE & QUEUE

Double-Ended Queue · Stack · Priority Queue

COLLECTIONS.DEQUE

"Always use deque for queues! List pop(0) is O(n), deque popleft() is O(1)."
from collections import deque
dq = deque([1,2,3])

dq.append(x)      # Push right
dq.appendleft(x)  # Push left
dq.pop()          # Pop right
dq.popleft()      # Pop left (O(1))

# BFS Pattern
queue = deque([root])
while queue:
    node = queue.popleft()

SLIDING WINDOW

A fixed-size deque auto-evicts old elements, making it perfect for sliding window analysis.

window = deque(maxlen=k)
for x in nums:
# Dijkstra pattern:
dist = {start: 0}
pq = [(0, start)]
while pq:
    d, u = heapq.heappop(pq)
    if d > dist.get(u, float('inf')):
        continue
    for v, w in graph[u]:
        nd = d + w
        if nd < dist.get(v, float('inf')):
            dist[v] = nd
            heapq.heappush(pq, (nd, v))

# Tie-breaking with counter (avoid comparing objects):
counter = 0
heapq.heappush(h, (priority, counter, item))
counter += 1

# Merge K sorted lists:
list(heapq.merge(*sorted_lists))

Collections Module

CHAPTER 07

Counters & Defaults

REF 7.1
from collections import Counter, defaultdict

# Frequency counting
c = Counter("aabbbcc")
c.most_common(2)  # [('b',3),('a',2)]

# Auto-init missing keys
adj = defaultdict(list)
adj[u].append(v)

Formatting & Bases

REF 7.2
f"{255:b}"       # 11111111 (binary)
f"{255:x}"       # ff (hex)
f"{x = }"        # x = 42 (debug!)

# Number bases
bin(42)  # '0b101010'
hex(42)  # '0x2a'
int('101010', 2)  # 42
Chapter 08 Algorithms: Timsort · Stable

SORTING · Ordering Logic

Python uses Timsort—a hybrid of Merge and Insertion sort. Worst case O(n log n), nearly-sorted O(n). All built-in sorts are stable.

METHODS

In-Place: .sort()
lst.sort()
lst.sort(reverse=True)
lst.sort(key=len)
Functional: sorted()
new = sorted(iterable)
new = sorted(d.items(), 
             key=lambda x: x[1])
Multi-Key Sorting
lst.sort(key=lambda x: (-x[0], x[1])) # Primary DESC, Secondary ASC

CUSTOM COMPARATORS

Use cmp_to_key for complex logic that doesn't fit a simple key function.

from functools import cmp_to_key

def compare(a, b):
    if str(a)+str(b) > str(b)+str(a):
        return 1
    return -1

nums.sort(key=cmp_to_key(compare))
Chapter 09

SLICING · Sequences

Syntax: [start:stop:step]. Stop is exclusive. Step -1 for reversal.

COMMON PATTERNS

s[0]      # First element
s[-1]     # Last element
s[::-1]   # Full reversal
s[:3]     # First 3 (0,1,2)
s[2:]     # From index 2 to end
s[::2]    # Every second element

UNPACKING

a, b, c = [1, 2, 3]
first, *rest = [1, 2, 3, 4]
# 1, [2, 3, 4]

a, b = b, a  # The Swap
The Walrus (3.8+)
if (n := len(a)) > 0: ...
Chapter 10 Syntactic Sugar

Comprehensions

Declarative creation of containers.

TYPES

List / Set
[x**2 for x in range(5)]
{x % 2 for x in nums}
# Filtered
[x for x in lst if x > 0]
Dict / Generator
{k: v for k, v in items}
# Lazy Generator
(x*x for x in big_list)
Nested Flattening
flat = [x for row in matrix for x in row]

PERFORMANCE

"List comprehensions are ~35% faster than for-loops. Use generator expressions (parentheses) to avoid memory spikes with large datasets."

Ternary Operator

val = x if x > 0 else -x
Chapter 11 Standard Library

Built-in Functions

Core utilities for functional programming.

POWER PATTERNS

# range tricks
range(10, 0, -1)   # 10,9,...,1
range(0, 10, 2)    # 0,2,4,6,8
list(range(5))       # [0,1,2,3,4]

# zip — stops at shortest!
zip([1,2],[3,4,5])  # (1,3),(2,4)
zip(*matrix)         # transpose matrix!

# enumerate from index 1:
enumerate(lst, 1)

# sum of diagonal:
sum(matrix[i][i] for i in range(len(matrix)))

# Fast modular exponentiation:
pow(2, 100, 10**9+7)  # 2^100 mod MOD

UTILITIES

# max with default (empty case):
max(lst, default=0)

# min index:
min(range(len(lst)), key=lambda i: lst[i])

# flatten iterables:
from itertools import chain
list(chain.from_iterable(nested))
Chapter 12 Combinatorics

itertools

High-performance iterator building blocks.

COMBINATORICS

from itertools import *

# Permutations (order matters)
permutations([1,2,3])        # all 3! arrangements
permutations([1,2,3], 2)     # choose 2
# → (1,2),(1,3),(2,1),(2,3),(3,1),(3,2)

# Combinations (order doesn't matter)
combinations([1,2,3], 2)     # choose 2
# → (1,2),(1,3),(2,3)

# Combinations with repetition
combinations_with_replacement([1,2], 2)
# → (1,1),(1,2),(2,2)

# Cartesian product
product([1,2], ['a','b'])     # all pairs
# → (1,'a'),(1,'b'),(2,'a'),(2,'b')
product(range(2), repeat=3)  # 3-bit binary numbers

ITERATORS & SEQUENCES

# Chaining & Grouping
chain([1,2], [3,4])          # 1,2,3,4
groupby([1,1,2,2,3])        # group consecutive

# Accumulate (prefix sum!)
accumulate([1,2,3,4])       # 1,3,6,10

# Infinite Sequences
count(10)                     # 10,11,12...
cycle([1,2,3])              # 1,2,3,1,2,3...
repeat(42, 5)               # 42 x5

# Slicing an iterator:
islice(count(1), 5)          # [1,2,3,4,5]
Chapter 13 Memoization

functools

Higher-order functions and caching patterns.

@lru_cache — MEMOIZATION

from functools import lru_cache, cache

# @cache = @lru_cache(maxsize=None)
@cache
def fib(n):
    if n <= 1: return n
    return fib(n-1) + fib(n-2)

# Management:
fib.cache_info()   # hits, misses, size
fib.cache_clear()  # clear cache

# Use functools.cached_property:
from functools import cached_property
class Tree:
    @cached_property
    def height(self): ...

REDUCE & PARTIAL

from functools import reduce, partial

# reduce(fn, iterable, initial)
reduce(lambda a, b: a*b, [1,2,3,4])

# partial — pre-fill arguments
def power(base, exp): return base**exp
square = partial(power, exp=2)

# total_ordering:
from functools import total_ordering
@total_ordering
class Node:
    def __eq__(self, o): return self.val == o.val
    def __lt__(self, o): return self.val < o.val
    # __le__, __gt__, __ge__ auto-generated!

Bit Operations

CHAPTER 14

Bitwise Operators

REF 14.1
x & y   # AND
x | y   # OR
x ^ y   # XOR
~x      # NOT (-(x+1))
x << n  # Left Shift
x >> n  # Right Shift
# Binary Rep
bin(5)      # '0b101'
int('101',2) # 5
5.bit_count() # 2 (3.10+)

DSA Tricks

REF 14.2
Power of Two?
x > 0 and (x & (x-1)) == 0
Odd/Even
x & 1 == 0 # Even

Math & Numbers

CHAPTER 15

The math Module

REF 15.1
import math

math.gcd(a, b)          # GCD (Euclidean)
math.lcm(a, b)          # LCM (3.9+)
math.comb(n, k)         # Combinations
math.isqrt(n)           # int sqrt
math.inf / math.pi      # Constants

Patterns

REF 15.2
# Fast Mod-Exp
pow(base, exp, MOD)

# Modulo (Cyclic)
arr[i % len(arr)]

# Rounding
a // b      # Floor
(a + b - 1) // b # Ceil

Flow & Patterns

CHAPTER 16

Pointer Logic

REF 16.1
# Two-pointer
l, r = 0, len(arr) - 1
while l < r:
    mid = (l + r) // 2
    if cond: r = mid
    else: l = mid + 1

# Sliding Window
for r in range(len(s)):
    window[s[r]] += 1
    while invalid:
        window[s[l]] -= 1
        l += 1

Structural Pattern Matching

REF 16.2
match command:
    case "quit": quit()
    case [x, y]: move(x, y)
    case {"id": i}: get(i)
    case _: print("default")

Modern Concurrency & Flow (3.11-3.14)

Free-Threaded CPython (3.13/3.14)

The Experimental Global Interpreter Lock (GIL) removal has reached official support in 3.14. CPU-bound multi-threaded Python programs can now execute across multiple cores simultaneously.

# Run python with: python -X gil=0

TaskGroups (3.11+)

A modernized, cleaner approach to running multiple asynchronous tasks safely. If one task fails, the remaining are immediately cancelled.

async with asyncio.TaskGroup() as tg:
    tg.create_task(job1())

Classes & OOP

CHAPTER 17

Common Data Structures

REF 17.1
class ListNode:
    def __init__(self, val=0, next=None):
        self.val, self.next = val, next

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val, self.left, self.right = val, left, right

class UnionFind:
    def __init__(self, n):
        self.parent = list(range(n))
        self.rank = [0] * n
    def find(self, x):
        if self.parent[x] != x:
            self.parent[x] = self.find(self.parent[x])
        return self.parent[x]
    def union(self, x, y):
        px, py = self.find(x), self.find(y)
        if px == py: return False
        if self.rank[px] < self.rank[py]: px, py = py, px
        self.parent[py] = px
        return True

Magic Methods & Dataclasses

REF 17.2
# Comparison for heapq
class Task:
    def __init__(self, priority, name):
        self.priority, self.name = priority, name
    def __lt__(self, other):
        return self.priority < other.priority

# Hashable for sets/dicts
class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y
    def __hash__(self):
        return hash((self.x, self.y))
    def __eq__(self, other):
        return (self.x, self.y) == (other.x, other.y)

# Modern Data Records
from dataclasses import dataclass
@dataclass
class State:
    node: int

Advanced Type System (3.11-3.14)

Self Type (3.11)

from typing import Self allows methods returning their own class instances to be properly typed without string references.

Type Parameters (3.12)

Generic classes and functions can now define type parameters directly inline: class List[T]: ....

Read-only Types (3.13)

typing.ReadOnly prevents mutating items in TypedDicts.

Type Aliases (3.12)

The type keyword creates native type aliases: type Point = tuple[int, int].

Exceptions & Debugging

CHAPTER 18

try/except Blocks

REF 18.1
try:
    result = risky_op()
except ValueError as e:
    print(f"Value error: {e}")
except (TypeError, IndexError):
    # catch multiple
except Exception as e:
    print(f"Unexpected: {type(e).__name__}: {e}")
else:
    # runs if NO exception
finally:
    # ALWAYS runs (cleanup)

# Raise
raise ValueError("bad input")
raise                    # re-raise current
raise TypeError() from None  # hide context

# Custom exception:
class GraphError(Exception): pass

Common DSA Exceptions

REF 18.2
IndexErrorList index out of range
KeyErrorDict key not found
ValueErrorWrong value
TypeErrorWrong type for operation
RecursionErrorMax recursion depth exceeded
StopIterationIterator exhausted
MemoryErrorOut of memory
DSA TIP

RecursionError is common in DFS — set sys.setrecursionlimit() for deep trees.

Modern Exceptions & Tracebacks (3.11-3.14)

Enhanced Tracebacks (3.11+)

Error tracebacks now precisely underline the exact expression that caused the exception, eliminating ambiguity in complex lines of code.

Exception Groups (3.11+)

The except* syntax allows handling multiple distinct exceptions raised simultaneously (often by TaskGroups).

try: ...
except* ValueError: ...

Simplified Except (3.14)

Parentheses are now optional when catching multiple exception types (unless using as).

except TypeError, ValueError:
    # No parentheses required

Complexity Quick Ref

CHAPTER 19

Big O Operations

REF 19.1
Data Structure Access Search Insert
listO(1)O(n)O(1)*
dict/setO(1)O(1)O(1)
dequeO(n)O(n)O(1)
heapqO(1)O(n)O(log n)

* amortized append

DSA Notes

REF 19.2
  • Python ints are arbitrary-precision (no overflow).
  • Timsort is O(n log n) worst/avg, O(n) best case.
  • Union-Find is nearly constant O(α(n)).
  • Search: Bisect (O(log n)) requires sorted input.