Interview Q&A · Python · 50 questions in this topic
Rapid-Fire Revision — Python Interview Q&A
The handbook's 50 rapid-fire question/answer pairs — one-line answers spanning the whole guide, for a final pass the night before an interview. Part of Rapid-Fire Revision · 375 questions in the Python bank.
Is Python interpreted or compiled?
Answer
Both — source compiles to bytecode, which the Python Virtual Machine then interprets.
Is Python strongly or weakly typed?
Answer
Strongly typed — it won't silently coerce incompatible types (e.g., "2" + 2 raises TypeError).
is vs ==?
Answer
is compares identity (same object in memory); == compares value.
Mutable vs immutable examples?
Answer
Mutable: list, dict, set. Immutable: int, str, tuple, frozenset.
Why are strings immutable?
Answer
Enables safe hashing (dict keys/sets), interning, and safe sharing across threads.
List vs tuple?
Answer
Lists are mutable and unhashable; tuples are immutable and hashable (if their contents are too).
What makes an object hashable?
Answer
Implementing __hash__ with a value that never changes, consistent with __eq__.
Shallow vs deep copy?
Answer
Shallow copies the outer object only; deep copy recursively copies every nested object too.
sort() vs sorted()?
Answer
sort() mutates a list in place and returns None; sorted() returns a new sorted list.
Fastest way to dedupe a list, preserving order?
Answer
list(dict.fromkeys(my_list)).
*args vs **kwargs?
Answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict.
The mutable default argument trap?
Answer
Default values are created once, at definition time — a mutable default (like []) is shared across every call.
What is a closure?
Answer
A nested function that remembers variables from its enclosing scope, even after that scope has returned.
Does Python support true method overloading?
Answer
No — a later same-named method definition silently replaces the earlier one.
@staticmethod vs @classmethod?
Answer
@staticmethod gets no automatic argument; @classmethod automatically receives cls.
What is MRO?
Answer
Method Resolution Order — the deterministic order Python searches ancestor classes, computed via C3 linearization.
What does super() actually call?
Answer
The next class in the current instance's MRO — not necessarily the immediate parent as written.
What is duck typing?
Answer
Python cares whether an object has the right behavior/ methods, not its declared type.
__str__ vs __repr__?
Answer
__str__ is a readable, user-facing string; __repr__ is an unambiguous, developer-facing one used as the fallback.
Key points
- 1Local — lives inside the current function; a variable assigned inside def f()
- 2Enclosing — an outer (non-global) function, for nested functions and closures; a variable in outer() referenced by inner()
- 3Global — the top level of the module; a variable assigned outside any function
- 4Built-in — Python's builtins module; len, print, Exception
Why does defining __eq__ risk breaking
Answer
hashing? Python sets __hash__ to None automatically unless you also define it yourself.
__new__ vs __init__?
Answer
__new__ creates the instance; __init__ initializes the already-created instance's state.
Composition vs inheritance?
Answer
Composition ("has-a") holds another object as an attribute; inheritance ("is-a") extends a base class directly.
try/except/else/finally order?
Answer
try → except → else (runs only if no exception) → finally (always runs).
Key points
- 1print — Python 2: a statement, print "hi"; Python 3: a function, print("hi")
- 2Division — Python 2: 5 / 2 == 2 (integer division); Python 3: 5 / 2 == 2.5 (true division)
- 3Strings — Python 2: str is bytes by default; Python 3: str is Unicode and bytes is separate
- 4input() — Python 2: input() evaluates the string, raw_input() returns it; Python 3: input() always returns str
- 5Maintenance — Python 2: end-of-life since January 2020; Python 3: actively developed
Why avoid a bare except:?
Answer
It also catches KeyboardInterrupt and SystemExit, which you almost never want to swallow.
EAFP vs LBYL?
Answer
EAFP ("easier to ask forgiveness") uses try/except; LBYL ("look before you leap") checks first with if. Python favors EAFP.
Iterable vs iterator?
Answer
An iterable produces an iterator via __iter__; an iterator tracks position via __next__.
yield vs return?
Answer
yield pauses and preserves state, resumable later; return exits the function permanently.
Can you re-iterate an exhausted generator?
Answer
No — once exhausted, it stays exhausted; you must create a new one.
What does functools.wraps fix?
Answer
It preserves a decorated function's __name__/__doc__ instead of showing the wrapper's.
How are stacked decorators applied vs
Answer
executed? Applied bottom-up (closest to the function first); executed topdown when called.
What does if __name__ == "__main__": do?
Answer
Runs code only when the file is executed directly, not when it's imported.
Why use a virtual environment?
Answer
Isolates a project's dependencies so different projects' package versions don't conflict.
Why is unpickling untrusted data dangerous?
Answer
Pickle can execute arbitrary code during deserialization — never unpickle untrusted input.
with open() vs manual open()/close()?
Answer
with guarantees the file closes even if an exception occurs inside the block.
What does __slots__ do?
Answer
Restricts instance attributes and removes the per-instance __dict__, saving memory.
What is a metaclass?
Answer
"The class of a class" — controls how classes themselves get created. Default is type.
What does @dataclass generate automatically?
Answer
__init__, __repr__, and __eq__, based on type-annotated class attributes.
namedtuple vs @dataclass?
Answer
namedtuple is immutable and tuple-like (indexable/ unpackable); @dataclass is more flexible with type hints and optional mutability.
Why is deque better than list for a queue?
Answer
deque.popleft() is O(1); list.pop(0) is O(n) since every element shifts.
What is the GIL?
Answer
CPython's lock allowing only one thread to run Python bytecode at a time.
Does the GIL affect I/O-bound threading?
Answer
No — the GIL is released during I/O waits, so threading still helps for I/O-bound work.
Threading vs multiprocessing, in one line?
Answer
Threading suits I/O-bound work (shared memory, GILlimited); multiprocessing suits CPU-bound work (separate processes, true parallelism).
What is a race condition?
Answer
Multiple threads modifying shared data concurrently, with the outcome depending on unpredictable timing.
How do you prevent a race condition?
Answer
Synchronize access with a threading.Lock, typically used as with lock:.
What's the common asyncio mistake with
Answer
sequential awaits? Awaiting tasks one after another runs them sequentially — use asyncio.gather() for real concurrency.
Concurrency vs parallelism?
Answer
Concurrency manages overlapping tasks (may take turns); parallelism runs tasks truly simultaneously on multiple cores.
CPU-bound vs I/O-bound?
Answer
CPU-bound spends time computing; I/O-bound spends time waiting on external resources.
How would you profile slow Python code?
Answer
cProfile first, to find the actual bottleneck before optimizing anything.
Optional[X] means what?
Answer
Shorthand for Union[X, None] — it describes the type, not whether there's a default value.
What's the single most common Python interview
Answer
trap overall? The mutable default argument — because defaults are evaluated once, at function definition time, not per call.
Recommended resourcesAffiliate links · may earn us a commission