Menu

Earn Premium with Referrals

Invite your friends and earn Premium rewards through our referral program.

See how it works and start inviting friends.

Part 4: Collections, Modules & Exceptions
PYTHON

Part 4: Collections, Modules & Exceptions

Revise Python collection performance, comprehensions, modules, packaging, imports, and exception handling.

1. List, dict, set, tuple — when to use

ContainerOrderedMutableComplexity of lookupsNotes
listyesyesO(n) index-by-value / O(1) by indexsequence, duplicates
tupleyesnoO(n) by valuefast, fixed, hashable
dictinsertion-ordered (3.7+)yesO(1) average key lookupkey→value
setunorderedyesO(1) unique membershipno duplicates
  • Dict/set lookup is O(1) but relies on hashes — keys must be hashable (immutable).
  • list membership test is O(n); set/dict membership O(1) — the classic performance question.

2. Comprehensions

  • List, dict, set comprehensions and generator expressions.
  • Readability + speed: usually faster than manual loops.
squares = [x*x for x in range(10) if x % 2 == 0]
d = {k: k**2 for k in range(5)}
g = (x for x in range(10))       # generator expression — lazy
  • Generator expression — lazy, one-shot; replaces intermediate lists.
  • Scoping: iteration variable is local to the comprehension — no leakage.

3. Iteration protocol & helpers

  • Iterator: an object with __next__(); triggers StopIteration when done.
  • Iterables implement __iter__ returning an iterator.
  • zip, enumerate, reversed, sorted, map, filter, itertools.* are the loop-helper kit.
  • itertools: chain, groupby, islice, permutations, combinations, product, count, cycle — interview favourites (lazy).

4. Modules, packages & imports

  • Each .py file is a module; a folder with __init__.py is a package.
  • Import caching: modules are imported once per interpreter (sys.modules cache) — imports are idempotent.
  • if __name__ == "__main__": guard — runs only when executed directly, not on import.
  • from x import * — wildcard imports are bad practice (namespace pollution); rely on __all__.
  • Relative imports from . import sibling for intra-package.
  • sys.path, PYTHONPATH, and the site-packages dirs.

Gotcha: importing a module that has side effects at top level runs them once — keep top-level clean.

5. Exceptions — the model

  • BaseExceptionException → specific types (ValueError, TypeError, KeyError, StopIteration, KeyboardInterrupt…).
  • try / except / else / finally: else runs only when no exception; finally always (cleanup).
  • except (A, B) catches multiple; Exception catch-all (avoid bare except:).
  • Raise: raise ValueError("msg"), bare raise re-raises, raise ... from cause chains.
  • Custom exceptions: subclass Exception.
  • assert — debugging aids; stripped by -O; never use for production validation (use explicit raises).
try:
    risky()
except (ValueError, TypeError) as e:
    handle(e)
else:
    print("no error")
finally:
    cleanup()

6. The stdlib interview box

  • collections.deque — fast appends both ends; defaultdict, Counter, OrderedDict, namedtuple.
  • datetime, math, re, json, os, pathlib, sys, random, functools, itertools.
  • with open(...) as f: — context manager guarantees file close.
  • pathlib over os.path — the modern path API.

7. Interview checkpoint

  • list vs set membership complexity; dict ordering.
  • Comprehension vs loop speed; generator laziness.
  • if __name__ == "__main__".
  • except ordering (most specific first), finally semantics.

My Private Notes

Notes are auto-saved locally to this device.