Python Data Structures Cheat Sheet

Here are the list, dictionary, and set operations you'll actually use, with how fast each one runs for when an interviewer asks why.

What's on the sheet

  • List. You want an ordered sequence you can index, grow, shrink, or scan.
  • Dictionary. You're looking things up by key, or grouping and counting by identity instead of position.
  • Set. You need uniqueness or a repeated membership check, and order never mattered anyway.

Watch out

  • List: insert() shifts every element after it down one slot, so it costs O(n). append() is the O(1) default, and we suggest insert() only when the position genuinely matters.
  • List: A grid built with [[0] * cols] * rows looks fine until you write to one cell. Every row is the same underlying list, so that write shows up in all of them. Build each row with its own list comprehension instead.
  • Dictionary: Reading a missing key from a defaultdict still creates it. Even a check like if d[key]: inserts the default value first. Use key in d when you only want to look, not write.
  • Dictionary: Counter's + - & | operators drop any key whose result lands at zero or below. Subtract two counters and the keys that cancelled out are gone entirely, not sitting at 0.
  • Set: Checking x in nums scans the whole list at O(n). The same check on a set is O(1). If a problem tests membership inside a loop, build the set first.
  • Set: Sets only hold hashable values, so a list can never go inside one. Need a set of groups, or a dict keyed by one? Convert each group to a tuple or frozenset first.

How to get it

This one is free and you don't need an account. Download the PDF above whenever you want it.

The ten pattern sheets work differently. You earn each one by solving half of that pattern's problems. See the pattern sheets.

Every pattern has a sheet too. See the full set.