1. List, dict, set, tuple — when to use
| Container | Ordered | Mutable | Complexity of lookups | Notes |
|---|---|---|---|---|
list | yes | yes | O(n) index-by-value / O(1) by index | sequence, duplicates |
tuple | yes | no | O(n) by value | fast, fixed, hashable |
dict | insertion-ordered (3.7+) | yes | O(1) average key lookup | key→value |
set | unordered | yes | O(1) unique membership | no duplicates |
- Dict/set lookup is O(1) but relies on hashes — keys must be hashable (immutable).
listmembership test is O(n);set/dictmembership 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__(); triggersStopIterationwhen 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
.pyfile is a module; a folder with__init__.pyis 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 siblingfor 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
- BaseException →
Exception→ specific types (ValueError,TypeError,KeyError,StopIteration,KeyboardInterrupt…). try / except / else / finally:elseruns only when no exception;finallyalways (cleanup).except (A, B)catches multiple;Exceptioncatch-all (avoid bareexcept:).- Raise:
raise ValueError("msg"), bareraisere-raises,raise ... from causechains. - 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.pathliboveros.path— the modern path API.
7. Interview checkpoint
list vs setmembership complexity; dict ordering.- Comprehension vs loop speed; generator laziness.
if __name__ == "__main__".exceptordering (most specific first),finallysemantics.
Premium Content
Unlock Part 4: Collections, Modules & Exceptions and all premium lessons with a subscription.
All premium lessons
Ad-free experience
Priority support
From ₹199.99/year — See plans