Python Cheatsheet

Essential Python tricks, patterns, and data structures for coding interviews — heaps, graphs, sorting, collections, and common algorithmic patterns

Heaps & Priority Queues (heapq)

Min-Heap Basics (great for Dijkstra's)

Python
import heapq

pq = []  # min-heap of (time, node)
heapq.heappush(pq, (0, source))
curr_time, curr_node = heapq.heappop(pq)

Heap Operations

Python
import heapq

# Tuple key (sorts by first element, then second)
h = []
heapq.heappush(h, (2, "love"))
heapq.heappush(h, (2, "i"))
heapq.heappush(h, (1, "coding"))

heapq.heappop(h)  # (1, 'coding')
heapq.heappop(h)  # (2, 'i')

# Heapify, peek, print sorted
h = [3, 1, 4]
heapq.heapify(h)
print(h[0])       # peek at minimum
print(sorted(h))  # sorted order

Custom Comparison for Max-Heap

Python
class RevStr(str):
    # Reverse lex order: "z" < "a"
    def __lt__(self, other):
        return self > other

Queues & Stacks

Using collections.deque

Python
from collections import deque

stack = deque()
stack.append(item)    # push
stack.pop()           # pop from right (stack)
stack.popleft()       # pop from left (queue)

Using a regular list

Python
stack = []
queue = []

# Stack operations
stack.append(item)
stack.pop()           # pop from right

# Queue operations (less efficient)
queue.append(item)
queue.pop(0)          # pop from left
Don't need hasVisited when exploring all paths (backtracking).

Dictionary Operations

Initialize with defaultdict (adjacency list)

Python
from collections import defaultdict

adj = defaultdict(list)
# No need to check if key exists
adj[node].append(neighbor)

Iterate over dict

Python
for key, value in d.items():
    print(key, value)

Remove key from dict

Python
del d["some_key"]
# Or safely (won't error if key missing)
d.pop("some_key", None)

Counter for frequency maps

Python
from collections import Counter

freq = Counter(words)
# freq["word"] gives count of "word"

2D Arrays & Copying

Initialize 2D array

Python
# m rows, n columns, all initialized to 1
d = [[1] * n for _ in range(m)]

Saving previous version of array

Python
# Make a shallow copy
temp = dist[:]

# Or use .copy()
previous = current.copy()

# Restricts calculations from ONLY the previous
# round — adds constraint of one-hop at a time
# (instead of multi-hops)!
Graph Algorithm Tip: Think through what memory is actually required. Dijkstra's with (u, v, w) tuples doesn't need an adjacency matrix — all info is already in the tuple!

List Operations

Remove an item from a list

Python
# Remove first occurrence of value
lst.remove(x)

# Remove using list comprehension
lst = [v for v in lst if v != x]

# Remove by index
del lst[i]

Sort a list

Python
lst.sort()  # in-place sort

Sort by lambda function

Python
lst.sort(key=lambda x: len(x))

# Equivalent shorthand
lst.sort(key=len)

Sort with custom key (multiple criteria)

Python
# Sort by frequency descending, then word ascending
result = sorted(
    ((f, str(w)) for f, w in heap),
    key=lambda x: (-x[0], x[1])
)

Append a copy to results

Python
res = []
res.append(path.copy())  # Important: copy!

String Operations

Join words into a sentence

Python
words = ["hello", "world", "from", "python"]
sentence = " ".join(words)
# Result: "hello world from python"

Convert character to integer

Python
# Character to ASCII value
ascii_val = ord('a')  # 97

# ASCII value to character
char = chr(97)  # 'a'

# Digit character to int
num = int('5')  # 5

Python Syntax Shortcuts

One-line if-else (ternary)

Python
status = "fast" if speed > 10 else "slow"

Infinity

Python
import math

positive_inf = math.inf
negative_inf = -math.inf

# Or using float
positive_inf = float('inf')
negative_inf = float('-inf')

Classes in Python

Basic class structure (Circular Queue example)

Python
class CircularQueue:
    def __init__(self, k: int):
        self.capacity = k
        self.queue = k * [0]
        self.headIndex = 0
        self.count = 0

    def enqueue(self, value: int) -> bool:
        if self.count == self.capacity:
            return False
        # Use mod for wrapping!
        tail = (self.headIndex + self.count) % self.capacity
        self.queue[tail] = value
        self.count += 1
        return True
Watch Out! Be careful about wrapping in circular data structures — use % capacity to handle wraparound.

Quick Reference

Min-heap push/pop
heapq.heappush(h, x) / heapq.heappop(h)
Adjacency list
adj = defaultdict(list)
Frequency count
freq = Counter(items)
2D array init
[[0] * n for _ in range(m)]
Queue (deque)
deque.append() / deque.popleft()
Stack (deque)
deque.append() / deque.pop()
Infinity
math.inf or float('inf')
Copy list
lst[:] or lst.copy()
Join strings
" ".join(words)
Char ↔ ASCII
ord('a') / chr(97)
Python Cheatsheet — essential patterns and data structures for coding interviews