Python Built-ins for Data Work
What this domain tests
Pure-Python mechanics behind every data script: variables and types, the core containers, file handling, control flow and functions. Questions are usually short code traces - predict the output or spot the bug.
Rules and concepts
- Names are bound to objects; assignment never copies a mutable object. b = a on a list means both names see the same list - use a[:] or list(a) to copy.
- Containers: list (ordered, mutable), tuple (ordered, immutable, hashable), set (unique, unordered), dict (key to value, hashable keys). Slices a[start:stop:step] exclude stop; negative indices count from the end.
- Dict access: d[k] raises KeyError when missing; d.get(k, default) and d.setdefault(k, []) do not.
- Files: with open(path, mode, encoding="utf-8") as f - modes "r", "w" (truncates), "a"; iterate the file object line by line. Always use with so the file is closed even on error.
- Control flow: if/elif/else, for over any iterable, while with a condition that changes, break/continue. 1 == True and 0 == False are both True.
- Functions: def with return; default arguments are evaluated once at definition, so never default to [] or {}; *args and **kwargs collect extras; locals shadow globals.
- Comprehensions: [f(x) for x in xs if cond] builds a list; {k: v for k, v in pairs} builds a dict.
Worked example
def add_item(item, bucket=[]): bucket.append(item) return bucket Calling add_item("a") then add_item("b") returns ['a'] then ['a', 'b'], because the default list is created once and shared. Fix it with bucket=None, then if bucket is None: bucket = [].
Traps
- Mutable default arguments; mutating a list while iterating it (iterate a copy instead).
- "w" mode silently erasing an existing file; omitting encoding for non-ASCII text.
- list.sort() returns None (use sorted()); "5" + 1 raises TypeError.
- / always gives a float, // floors, and -7 // 2 is -4.
- Comparing floats with == instead of math.isclose.