Skip to content

alphaPlan · Data Structures, Algorithms & the Web · Cheat-sheet 02

Collections and data types

Pick the right container for the job: tuples that never change, dictionaries that look up by key, sets with no duplicates, and files that outlive the program.

Ideas to remember

  1. 01A tuple is written with round brackets and is immutable: you cannot append to it, delete from it, or reassign one of its slots.
  2. 02A dictionary stores key and value pairs in curly braces, so you look things up by a meaningful name instead of a numeric position.
  3. 03A set holds each item only once and has no order, and testing x in a set stays near instant as the set grows.
  4. 04Union |, intersection & and difference - answer plain questions about two groups in a single symbol.
  5. 05A file keeps data on disk: open it with a mode, read or write, then close it, and a with block closes it for you even if an error strikes.
  6. 06Reach for a tuple when position has fixed meaning, a list when items come and go, a dictionary to tally or look up, and a set for fast membership.

Words

a, b = b, a
Unpacking swaps two values without a temporary variable.
return area, perimeter
Quietly builds a tuple, so one return hands back several results at once.
counts.get(word, 0) + 1
The old count, or 0 if this is the first time, plus one; .get() names a fallback for a missing key.
list(set(ids))
Pours a list into a set to drop the duplicates, then back into a list.
with open(...) as f:
Opens the file and closes it for you automatically when the indented block ends.
r, w, a
The file modes: r reads, w starts a fresh empty file and erases an existing one, a appends to the end and keeps what is there.

Do this

  • Test with in or fetch with .get() and a default when you are not certain a key is in the dictionary.
  • Wrap two lists in set(...) and use & to find what they have in common in one line.
  • Use with every time you open a file, and state the utf-8 encoding so Albanian letters survive moving between computers.
  • Catch FileNotFoundError with try and except and set a sensible default so the program keeps going.
  • To change a tuple, build a new one: convert to a list, edit it, and convert back.

Watch out

  • Reading a missing key with square brackets raises a KeyError and halts the program; this is the most common dictionary mistake.
  • Opening an existing file with mode w erases it the instant you open it, before you write anything; use a to keep what is there.
  • The order you see when you print a set is arbitrary and not something to rely on; if order matters, a set is the wrong tool.

Found something unclear, outdated or improvable? Suggest an improvement