Miscellaneous: Comprehensions, Lambdas, Closures, I/O
Comprehensions, Lambdas, Closures, I/O
List comprehensions [expr for x in it if cond] build lists eagerly; generator expressions (expr for x in it) are lazy. Dict/set comprehensions use {k: v ...} and {x ...}. Nested comprehensions read left to right as nested loops. Candidates must know that the loop variable leaks in Python 2 but not in Python 3 (comprehensions have their own scope).
Lambdas are anonymous single-expression functions; they cannot contain statements. Closures capture variables by reference, not value-late binding means a lambda inside a loop sees the final value unless bound via a default argument (lambda x=i: x). nonlocal lets a nested function rebind an enclosing variable; global targets module scope. The functools module offers partial for pre-binding arguments.
File I/O: open(path, mode) with modes r, w (truncates), a, x, b, +. Prefer with open(...) as f: for guaranteed closing. Iterating a file yields lines including trailing newlines; use .strip(). f.read() returns all text, f.readline() one line, f.readlines() a list.
Traps: sorted(data, key=lambda p: p[1]) versus calling the lambda; using a comprehension for side effects; assuming a generator can be iterated twice (it is exhausted); and w mode silently erasing a file. Worked example: [i*i for i in range(4) if i % 2] → [1, 9]. Rule of thumb: comprehensions for building, generators for streaming, with for files.