N python cheat sheet: the 5 bits of syntax coding interviews lean on, with an example for each - Netscape _ □ ×
Back Forward Home Reload Guides Sign
URL: http://www.nicnonac.com/guides/python-cheat-sheet/
☷ python cheat sheet: the 5 bits of syntax coding interviews lean on, with an example for each - nicnonac guides _□×

← back to guides

python cheat sheet: the 5 bits of syntax coding interviews lean on, with an example for each

Stacks · 10 min read · posted Nov 30, 2026, 2:34 pm

Most of the Python you write in a coding interview leans on the same five bits of syntax. Once they're automatic, your attention goes on the problem instead of on where the colon goes.

This is the cheat sheet from the reel. It covers the five things in it. For each one you get where it shows up in interview problems, the syntax with a small example and what it prints, the mistake that usually breaks it, and problems to practise on, easiest first.

I spent about three months preparing for my Atlassian internship interviews, and my notes are all in Python. All five of these are in them. None of the problems below come from an interview. They're all public on LeetCode.

Every block here was run on Python 3.11, and the output under it is what it printed. Anything from 3.10 up prints the same.

the quick lookup

i need to write
build a list from another list [x * x for x in nums]
keep only some of the items [x for x in nums if x > 0]
a grid of zeros [[0] * cols for _ in range(rows)]
the last item nums[-1]
everything but the first nums[1:]
reverse a list or a string nums[::-1]
a copy of a list nums[:]
count everything Counter(nums)
the k most common Counter(nums).most_common(k)
read a key that might be missing d.get(key, 0)
a dict of lists defaultdict(list)
sort by one field sorted(rows, key=lambda r: r[1])
sort biggest first sorted(nums, reverse=True)
sort by two things key=lambda r: (r[1], r[0])
the index and the value for i, x in enumerate(nums):
walk two lists together for a, b in zip(xs, ys):
each item next to the one after it zip(nums, nums[1:])

Counter and defaultdict come from collections. Everything else on this page is built in.

1. list comprehensions

Where it shows up. Any time you're about to write out = [] and then a loop that appends. Building the answer list, filtering the input, and setting up a DP table are all this.

The syntax. [expression for x in items if condition]. It reads like the loop it replaces: the for and the if stay in the same order, and the thing you would have appended moves to the front.

nums = [3, 8, 1, 6, 4]

out = []
for x in nums:
    if x % 2 == 0:
        out.append(x * x)
print(out)

print([x * x for x in nums if x % 2 == 0])
[64, 36, 16]
[64, 36, 16]

This is the one in the reel. The 3 and the 1 fail the filter, and the other three are squared on their way into the new list.

Other shapes. Curly brackets give you a dict or a set. An if ... else at the front picks a value for every item, where an if at the end drops items. Two fors nest in the order you'd write the loops. Without brackets inside sum, max or any, it's a generator, which never builds the list at all.

words = ["tree", "trie", "try"]
print({w: len(w) for w in words})
print({w[0] for w in words})
print(["even" if x % 2 == 0 else "odd" for x in [3, 8, 1]])
print([(r, c) for r in range(2) for c in range(3)])
print(sum(x * x for x in [1, 2, 3]))
{'tree': 4, 'trie': 4, 'try': 3}
{'t'}
['odd', 'even', 'odd']
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]
14

What breaks it. Building a grid by multiplying a list of lists. [[0] * 3] * 3 is three references to the same row, so changing one cell changes a whole column. Build each row in a comprehension instead, which is how my notes build every 2D table.

bad = [[0] * 3] * 3
bad[0][0] = 1
print(bad)

good = [[0] * 3 for _ in range(3)]
good[0][0] = 1
print(good)
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
[[1, 0, 0], [0, 0, 0], [0, 0, 0]]

[0] * 3 on its own is fine, because numbers can't be changed in place. It's only lists inside lists that bite. The other mistake is squeezing too much into one line. If it needs two conditions and a nested loop, write the loop. The interviewer has to read it too.

Practise.

2. slicing

Where it shows up. Palindromes, reversing, rotating, splitting an array into halves, "everything after the first", the last cell of a DP table, and copying the current path in backtracking with path[:].

The syntax. nums[start:stop:step]. The start is included and the stop isn't. Leave any of them out and they default to the beginning, the end and 1. A negative index counts from the end, so -1 is the last item. A negative step walks backwards.

nums = [10, 20, 30, 40, 50, 60]
print(nums[1:4])
print(nums[-2:])
print(nums[::-1])
print(nums[::2])
print(nums[:-1])
print(nums[-1])
[20, 30, 40]
[50, 60]
[60, 50, 40, 30, 20, 10]
[10, 30, 50]
[10, 20, 30, 40, 50]
60

The first three are the ones in the reel. nums[1:4] stops before index 4, so it's three items, which is stop - start. Strings slice the same way, which makes a palindrome check one line.

s = "racecar"
print(s == s[::-1])
print("hello"[1:4])
True
ell

Second shape: change the list in place. A slice on the left of = replaces those items in the original list. Rotating right by k is the last k items followed by the rest.

def rotate(nums, k):
    k %= len(nums)
    nums[:] = nums[-k:] + nums[:-k]

nums = [1, 2, 3, 4, 5]
rotate(nums, 2)
print(nums)
rotate(nums, 7)
print(nums)
[4, 5, 1, 2, 3]
[2, 3, 4, 5, 1]

The k %= len(nums) matters. Rotating 5 numbers by 7 is the same as rotating by 2, and without that line nums[-7:] is the whole list and nothing moves.

What breaks it. Forgetting that a slice is a new list. In Reverse String you have to change the list you were given, and s = s[::-1] only points your local name at a reversed copy. The caller's list never changes.

def reverse_bad(s):
    s = s[::-1]

def reverse_good(s):
    s[:] = s[::-1]

a = ["h", "i", "!"]
reverse_bad(a)
print(a)
reverse_good(a)
print(a)
['h', 'i', '!']
['!', 'i', 'h']

The copy costs time too. A slice of k items is O(k), so recursion that passes nums[1:] down at every level is O(n²) without a loop in sight. My notes flag exactly this on the build-a-tree-from-traversals problem: pass indexes instead. Slices are forgiving at the edges, though. nums[1:100] just stops at the end, where nums[100] raises an IndexError.

Practise.

3. dicts and counter

Where it shows up. "How many times", "most frequent", "first unique", anagrams, and anything you group by a shared key. Why a dict lookup is O(1), and the two sum template built on it, are in the data structures cheat sheet. This section is the syntax.

The syntax. Counting by hand, d.get(key, 0) reads a key that might not be there and gives you 0 instead of an error. Counter does the whole loop in one call, and most_common(k) gives back the k biggest counts, biggest first.

from collections import Counter

pets = ["cat", "dog", "cat", "owl", "cat", "dog"]

cnt = {}
for p in pets:
    cnt[p] = cnt.get(p, 0) + 1
print(cnt)

cnt = Counter(pets)
print(cnt)
print(cnt.most_common(1))
print(cnt["fox"])
{'cat': 3, 'dog': 2, 'owl': 1}
Counter({'cat': 3, 'dog': 2, 'owl': 1})
[('cat', 3)]
0

This is the one in the reel. A Counter answers 0 for a key it has never seen, where a plain dict raises an error. Dicts keep keys in the order they were added, and most_common breaks ties the same way: first seen, first listed.

Second shape: a dict of lists. defaultdict(list) makes the empty list for you the first time a key is used, so you can append straight away.

from collections import defaultdict

words = ["tree", "try", "cat", "trie", "cow"]
by_first = defaultdict(list)
for w in words:
    by_first[w[0]].append(w)
print(dict(by_first))
{'t': ['tree', 'try', 'trie'], 'c': ['cat', 'cow']}

Counters compare and subtract. Two words are anagrams when their counts are equal. Subtracting keeps only what's left over above zero, which is the whole of Ransom Note: an empty result means the magazine had every letter.

from collections import Counter

print(Counter("listen") == Counter("silent"))
print(Counter("aab") - Counter("ab"))
print(not (Counter("aa") - Counter("aab")))
True
Counter({'a': 1})
True

What breaks it. += on a key a plain dict has never seen.

cnt = {}
cnt["cat"] += 1
KeyError: 'cat'

Use .get, a Counter or a defaultdict. The opposite trap is a defaultdict that grows when you only meant to look. Reading a missing key with square brackets adds it, so check with in first.

from collections import defaultdict

d = defaultdict(list)
print("x" in d)
d["x"]
print("x" in d)
False
True

Practise.

4. sorting with a key

Where it shows up. Intervals, which you nearly always sort by start first. "Sort by frequency", "sort the people by height", and greedy problems where handling things in the right order is the whole trick.

The syntax. sorted(items, key=...) calls the key function once on each item and sorts by what it returns. reverse=True puts the biggest first. sorted returns a new list. items.sort(...) takes the same arguments and sorts the list in place.

rows = [("ana", 31), ("ben", 25), ("cy", 42), ("di", 25)]

print(sorted(rows, key=lambda r: r[1]))
print(sorted(rows, key=lambda r: r[1], reverse=True))
[('ben', 25), ('di', 25), ('ana', 31), ('cy', 42)]
[('cy', 42), ('ana', 31), ('ben', 25), ('di', 25)]

This is the one in the reel. Ben and Di are both 25, and Ben stays ahead of Di both times. Python's sort is stable: items with equal keys keep the order they came in, even with reverse=True.

Second shape: sort by two things. Return a tuple and Python compares the first parts, then the second where those tie. A minus sign flips one number on its own. This is Sort Array by Increasing Frequency: least frequent first, and the bigger number first on a tie.

from collections import Counter

nums = [1, 1, 2, 2, 2, 3]
cnt = Counter(nums)
print(sorted(nums, key=lambda x: (cnt[x], -x)))
[3, 1, 1, 2, 2, 2]

You can't put a minus in front of a string. To get names Z to A inside ages low to high, sort twice, by the less important key first. Stability keeps the first order wherever the second sort sees a tie.

rows = [("ana", 31), ("ben", 25), ("cy", 42), ("di", 25)]
rows.sort(key=lambda r: r[0], reverse=True)
rows.sort(key=lambda r: r[1])
print(rows)
[('di', 25), ('ben', 25), ('ana', 31), ('cy', 42)]

max and min take a key too, so max(rows, key=lambda r: r[1]) is the oldest person without sorting anything.

What breaks it. Assigning the result of .sort(). It sorts in place and returns None, so the next line fails on a list that's gone.

nums = [3, 1, 2]
nums = nums.sort()
print(nums)
None

Write nums.sort() on its own line, or nums = sorted(nums). And remember the sort itself costs O(n log n). If the question wants O(n), sorting is the step to get rid of.

Practise.

5. enumerate and zip

Where it shows up. You need the index as well as the value, like when a hash map stores where it saw each number. Two lists that line up, like the positions and speeds in Car Fleet. Comparing each item with the next one.

The syntax. enumerate(items) hands you (index, item) each time round. zip(a, b) hands you one item from each list, side by side. for i, n in ... unpacks the pair into two names.

names = ["ana", "ben", "cy"]
ages = [31, 25, 42]

for i, n in enumerate(names):
    print(i, n)

for n, a in zip(names, ages):
    print(n, a)
0 ana
1 ben
2 cy
ana 31
ben 25
cy 42

This is the one in the reel. No range(len(names)) and no names[i].

Other shapes.

nums = [5, 7, 7, 9]
print(list(enumerate(nums, start=1)))
print({x: i for i, x in enumerate(nums)})
print([b - a for a, b in zip(nums, nums[1:])])
print(dict(zip(["ana", "ben"], [31, 25])))
print([list(row) for row in zip(*[[1, 2, 3], [4, 5, 6]])])
[(1, 5), (2, 7), (3, 7), (4, 9)]
{5: 0, 7: 2, 9: 3}
[2, 0, 2]
{'ana': 31, 'ben': 25}
[[1, 4], [2, 5], [3, 6]]

In order: counting from 1, a map from each value to its index (a repeated value keeps its last index, here 7 goes to 2), the gap between each pair of neighbours, two lists into one dict, and zip(*grid), which turns rows into columns. That last one is all of Transpose Matrix.

What breaks it. zip stops at the shortest list without telling you. If the lists should be the same length, strict=True (Python 3.10 and up) makes it raise instead.

print(list(zip([1, 2, 3], ["a", "b"])))
print(list(zip([1, 2, 3], ["a", "b"], strict=True)))
[(1, 'a'), (2, 'b')]
ValueError: zip() argument 2 is shorter than argument 1

The other one: zip and enumerate give you something you can only walk through once. Save it with list(...) if you need it twice.

pairs = zip([1, 2], ["a", "b"])
print(list(pairs))
print(list(pairs))
[(1, 'a'), (2, 'b')]
[]

Practise.

how to practise with this

One section at a time. Do the easy problems with the page open, then come back a day later and do them again with it closed. Syntax sticks from typing it, not from reading it.

When a solution works, look for the loop that builds a list, the range(len(...)), or the dict you fill by hand. Those are the spots one of these five makes shorter, and shorter code is less to explain out loud.

honest limitations

Five bits of syntax isn't all of Python. heapq, deque and @cache turn up just as often. They're covered where they get used, in the coding interview cheat sheet and the data structures one linked above.

Shorter isn't always better in an interview. A comprehension with two conditions and a nested loop is harder to talk through than the loop it replaced. Use these where they make the code clearer, not to show you know them.

Everything here was run on Python 3.11. strict=True on zip needs 3.10 or newer, and dicts have kept insertion order since 3.7.

← all guides

Done nicnonac.com 56.6k