Data model, collections, comprehensions, generators, decorators, typing
Practise these as flashcards. One or two lines each; the ones you miss come back first.
Start freeA list is mutable, so you can change its elements, while a tuple is immutable and cannot be changed after creation. Lists use square brackets, tuples use parentheses.
You can copy a list with list.copy() or slicing. A shallow copy only copies the outer list, so nested objects are shared. A deep copy, using copy.deepcopy, recursively copies everything, so changes to nested objects don't affect the original.
with statement do?The with statement is used with context managers to ensure resources are properly managed. For example, it automatically closes a file after you're done reading or writing.
*args do in a function definition?*args collects any extra positional arguments passed to a function into a tuple, allowing you to accept a variable number of arguments.
Both dict and set use hash tables, so average-case lookup, insert, and delete operations are O(1). However, in rare cases of hash collisions, the worst case can degrade to O(n), but this is uncommon in practice.
A generator produces items one at a time using yield, so it doesn't store all items in memory. A list comprehension creates the entire list in memory. Generators are useful for large or infinite data streams.
You create a custom exception by subclassing Exception. This makes your error handling more explicit and helps callers distinguish different error types in your code.
A closure is an inner function that remembers variables from its enclosing scope, even after the outer function has finished executing. This allows you to create functions with persistent state.
I use None as the default value and then set the actual default inside the function. For example: def f(x, l=None): if l is None: l = [].
I use the @property decorator to define a method that acts like an attribute. This lets me control access or computation when getting or setting a value.
The GIL means only one thread can execute Python bytecode at a time, so threads don't help for CPU-bound tasks. For I/O-bound tasks, threads are still useful because they can release the GIL while waiting.
A dataclass automatically generates methods like __init__, __repr__, and __eq__ based on the fields you define, reducing boilerplate. Regular classes require you to write these methods yourself.