Python Data Structures Cheat Sheet

The operations you actually reach for on a list, a dictionary, and a set, with the time complexity that matters when an interviewer asks why.

What's on the sheet

  • List. An ordered, indexable sequence you will grow, shrink, or scan.
  • Dictionary. Key-based lookups, grouping, or counting, anything you index by identity instead of position.
  • Set. Uniqueness or a membership check you will run more than once, when 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; reach for 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, O(n). The identical 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

Free. No account needed. Download the PDF above whenever you want it.

The ten pattern sheets work differently: solve half of a pattern's problems and you earn that sheet for free, or get every one right away as a member. See the pattern sheets.

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