Goal: Python syntax for LeetCode-style interviews.
Focus: essential syntax and patterns, not a comprehensive Python reference.


PAGE 1 — Core Python Syntax

1. Variables & Basic Operations

x = 5
a, b = 1, 2
a, b = b, a                  # swap

x += 1
x -= 1
x *= 2
x //= 2                     # integer division

abs(x)
min(a, b)
max(a, b)
sum(nums)

2. Strings

s = "Hello"

len(s)
s[i]                        # character
s[i:j]                      # substring
s[::-1]                     # reverse

s.lower()
s.upper()
s.strip()

s.split()                   # "a b c" -> ["a", "b", "c"]
" ".join(words)             # ["a", "b"] -> "a b"
"".join(sorted(s))          # sorted characters

s.isalpha()
s.isdigit()
s.isalnum()

Character ↔ ASCII

ord('a')                    # 97
chr(97)                     # 'a'

Common string loops

for c in s:
    ...

for i, c in enumerate(s):
    ...

3. Lists / Arrays

nums = []
nums = [1, 2, 3]

len(nums)

nums.append(x)
nums.pop()                  # remove last
nums.pop(i)                 # remove index i

nums[i]
nums[i:j]

nums.reverse()              # in-place
nums.sort()                 # in-place

sorted(nums)                # returns new list

Useful shortcuts

nums = [0] * n              # [0, 0, 0, ...]

nums = list(range(n))       # [0, 1, 2, ..., n-1]

nums = list(range(1, n + 1))

x = nums[-1]                # last
x = nums[-2]                # second last

Looping

for x in nums:
    ...

for i in range(len(nums)):
    ...

for i, x in enumerate(nums):
    ...

for a, b in zip(nums1, nums2):
    ...

List comprehension

squares = [x * x for x in nums]

even = [x for x in nums if x % 2 == 0]

zeros = [0 for _ in range(n)]

4. HashMap / Dictionary ⭐

Initialize

mp = {}

Insert / update

mp[key] = value

mp[key] += 1

If key might not exist:

mp[key] = mp.get(key, 0) + 1

Check

if key in mp:
    ...

if key not in mp:
    ...

Get

value = mp[key]

value = mp.get(key)         # None if missing
value = mp.get(key, 0)      # 0 if missing

Loop

for key in mp:
    ...

for key, value in mp.items():
    ...

Frequency Map

count = {}

for x in nums:
    count[x] = count.get(x, 0) + 1

Dictionary comprehension

mp = {x: 0 for x in nums}

5. Set ⭐

seen = set()

seen.add(x)
seen.remove(x)              # must exist
seen.discard(x)             # safe if missing

if x in seen:
    ...

len(seen)

Convert

set(nums)
list(set(nums))

Classic “seen” pattern

seen = set()

for x in nums:
    if x in seen:
        return True
    seen.add(x)

6. Sorting ⭐

nums.sort()                 # modify nums
nums.sort(reverse=True)

sorted_nums = sorted(nums)

sorted(nums, reverse=True)

Sort with key

items.sort(key=lambda x: x[0])

items.sort(key=lambda x: x[1], reverse=True)

sorted(items, key=lambda x: x[0])

Sort by multiple fields

items.sort(key=lambda x: (x[0], -x[1]))

Zip + sort + unpack

time_sorted = sorted(
    zip(position, speed),
    key=lambda x: x[0],
    reverse=True
)

position, speed = zip(*time_sorted)

7. Tuples

t = (1, 2)

a, b = t

x, y = y, x

Useful for coordinates

r, c = (2, 3)

queue.append((r, c))

Unpacking

for r, c in points:
    ...

8. Conditionals / One-Liners

if x > 0:
    ...

if x > 0:
    ...
else:
    ...

Ternary

x = a if condition else b

Example:

mx = a if a > b else b

Multiple conditions

if x > 0 and y > 0:
    ...

if x == 0 or y == 0:
    ...

if not seen:
    ...

PAGE 2 — DSA Coding Patterns

9. Two Pointers ⭐

left = 0
right = len(nums) - 1

while left < right:
    if nums[left] + nums[right] == target:
        return [left, right]
    elif nums[left] + nums[right] < target:
        left += 1
    else:
        right -= 1

String version

left = 0
right = len(s) - 1

while left < right:
    ...
    left += 1
    right -= 1

10. Sliding Window ⭐

Basic template

left = 0

for right in range(len(nums)):
    # add nums[right]

    while condition:
        # remove nums[left]
        left += 1

    # update answer

With HashMap

window = {}
left = 0

for right, c in enumerate(s):
    window[c] = window.get(c, 0) + 1

    while ...:
        window[s[left]] -= 1
        left += 1

11. Stack ⭐

Python list = stack.

stack = []

stack.append(x)             # push
x = stack.pop()             # pop
x = stack[-1]               # peek

if stack:
    ...

Common monotonic-stack pattern

for x in nums:
    while stack and stack[-1] < x:
        stack.pop()

    stack.append(x)

12. Queue / BFS ⭐

Don’t use pop(0) — it is O(n).

from collections import deque

q = deque()

q.append(x)
x = q.popleft()

BFS

q = deque([start])

while q:
    node = q.popleft()

    for nei in graph[node]:
        q.append(nei)

Grid BFS directions

dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]

for dr, dc in dirs:
    nr = r + dr
    nc = c + dc

13. Heap / Priority Queue ⭐

Python provides a min heap.

import heapq

heap = []

heapq.heappush(heap, x)
x = heapq.heappop(heap)

x = heap[0]                 # smallest

Build heap

heapq.heapify(nums)

Max heap

Negate values:

heapq.heappush(heap, -x)

x = -heapq.heappop(heap)

Heap of tuples

heapq.heappush(heap, (priority, value))

Python compares tuples from left to right, so priority is used first.


14. Binary Search ⭐

Basic template

left = 0
right = len(nums) - 1

while left <= right:
    mid = (left + right) // 2

    if nums[mid] == target:
        return mid
    elif nums[mid] < target:
        left = mid + 1
    else:
        right = mid - 1

return -1

Python shortcut

import bisect

i = bisect.bisect_left(nums, target)

bisect_left = first position where target can be inserted.


15. Graph

Adjacency List

graph = {}

graph[u] = []
graph[u].append(v)

Usually easier:

from collections import defaultdict

graph = defaultdict(list)

graph[u].append(v)
graph[v].append(u)

Recursive DFS

def dfs(node):
    if node in seen:
        return

    seen.add(node)

    for nei in graph[node]:
        dfs(nei)

Iterative DFS

stack = [start]
seen = set()

while stack:
    node = stack.pop()

    if node in seen:
        continue

    seen.add(node)

    for nei in graph[node]:
        stack.append(nei)

16. Common collections

from collections import Counter, defaultdict, deque

Counter

count = Counter(s)

count['a']

count.most_common(1)

Instead of:

count = {}

for c in s:
    count[c] = count.get(c, 0) + 1

defaultdict

graph = defaultdict(list)

graph[x].append(y)

deque

q = deque()

q.append(x)
q.popleft()

17. Useful Built-ins

len(nums)
sum(nums)
min(nums)
max(nums)

any(condition for x in nums)
all(condition for x in nums)

enumerate(nums)
zip(a, b)

range(n)
range(start, end)
range(start, end, step)

Examples

any(x > 10 for x in nums)

all(x >= 0 for x in nums)

18. The 10 Syntax Patterns to Memorize First ⭐⭐⭐

If you’re just getting back into coding, memorize these first. Don’t try to memorize the whole sheet.

# 1. HashMap
mp = {}
mp[x] = mp.get(x, 0) + 1

# 2. Set
seen = set()
seen.add(x)
if x in seen:
    ...

# 3. Loop with index
for i, x in enumerate(nums):
    ...

# 4. Reverse
s[::-1]

# 5. Sort
nums.sort()
sorted(nums)

# 6. Sort with key
sorted(items, key=lambda x: x[1])

# 7. Stack
stack.append(x)
stack.pop()

# 8. Queue
from collections import deque
q = deque()
q.append(x)
q.popleft()

# 9. Heap
import heapq
heapq.heappush(heap, x)
heapq.heappop(heap)

# 10. Two pointers
left, right = 0, len(nums) - 1

while left < right:
    ...
    left += 1
    right -= 1

19. Three Loop Patterns You Should Instantly Recognize

Iterate values

for x in nums:
    ...

Iterate indexes

for i in range(len(nums)):
    ...

Iterate index + value

for i, x in enumerate(nums):
    ...

20. Quick Mental Reference

When you’re staring at a LeetCode problem and can’t remember syntax:

NeedPython
HashMapmp = {}
HashMap frequencymp[x] = mp.get(x, 0) + 1
Setseen = set()
Add to setseen.add(x)
Check setif x in seen:
Stackstack = []
Pushstack.append(x)
Popstack.pop()
Queueq = deque()
Enqueueq.append(x)
Dequeueq.popleft()
Heapheapq.heappush(heap, x)
Remove heapheapq.heappop(heap)
Sortsorted(nums)
In-place sortnums.sort()
Reverses[::-1]
Lengthlen(x)
Index + valueenumerate(nums)
Pair arrayszip(a, b)
Integer divisiona // b
Remaindera % b
First/lastnums[0], nums[-1]
Subarraynums[l:r]
Rangerange(n)
Min/maxmin(), max()
Absoluteabs(x)

Final Rule

Don’t expand this cheat sheet too quickly.

You already know the DSA concepts. Your current bottleneck is Python muscle memory.

Practice like this:

Problem
Identify DSA pattern
Open cheatsheet only for syntax
Write code yourself
Get stuck
Add ONLY that missing syntax/pattern

The objective is to eventually stop looking at the sheet — not to build the world’s most impressive Python cheat sheet.