Interview: Python Fundamentals
Common Python interview questions and answers — data types, memory, GIL, decorators, generators, and OOP concepts.
These questions appear in nearly every Python interview. Understand the why, not just the answer.
Data Types & Mutability
Q: What’s the difference between a list and a tuple?
Lists are mutable, tuples are immutable. Tuples can be dict keys and function return values. Lists use more memory but support in-place modification.
Q: Are Python integers mutable?
Integers are immutable. x += 1 creates a new int object; it doesn’t modify the original.
Q: What is None?
None is a singleton object representing absence of value. It’s falsy and has type NoneType.
Memory & References
Q: How does Python handle memory?
Reference counting with a generational garbage collector for circular references. Objects are deallocated when reference count hits zero.
Q: Shallow copy vs deep copy?
import copy
shallow = original.copy() # new outer, shared inner objects
deep = copy.deepcopy(original) # fully independent
Q: What happens here?
def add_item(item, lst=[]):
lst.append(item)
return lst
Mutable default argument — the list is created once and shared across all calls. Fix with lst=None and if lst is None: lst = [].
The GIL
Q: What is the Global Interpreter Lock?
A mutex that allows only one thread to execute Python bytecode at a time. It prevents true CPU parallelism for threads but doesn’t block I/O operations (which release the GIL).
Q: How do you achieve parallelism in Python?
- I/O-bound:
threading,asyncio, orThreadPoolExecutor - CPU-bound:
multiprocessingorProcessPoolExecutor
Functions & Closures
Q: Explain *args and **kwargs.
*args collects extra positional arguments as a tuple. **kwargs collects extra keyword arguments as a dict.
Q: What is a closure?
A function that captures variables from its enclosing scope:
def multiplier(factor):
def multiply(x):
return x * factor
return multiply
double = multiplier(2)
double(5) # 10
Q: What does @functools.wraps do?
Preserves the original function’s __name__, __doc__, and other metadata when wrapping with a decorator.
OOP
Q: @staticmethod vs @classmethod vs instance method?
| Type | First arg | Use case |
|---|---|---|
| Instance | self |
Access instance state |
@classmethod |
cls |
Alternative constructors, class-level ops |
@staticmethod |
none | Utility function in class namespace |
Q: What is MRO (Method Resolution Order)?
The order Python searches base classes when resolving methods. Use ClassName.__mro__ or ClassName.mro() to inspect.
Q: Composition vs inheritance?
Prefer composition (“has-a”) over inheritance (“is-a”) when possible. Composition is more flexible and avoids deep inheritance hierarchies.
Generators & Iterators
Q: Generator vs list comprehension?
Generators are lazy — they yield one item at a time using constant memory. List comprehensions build the entire list in memory.
Q: What does yield do?
Pauses the function and returns a value. Calling the generator again resumes from where it left off.
Decorators
Q: How do decorators work?
@decorator is syntactic sugar for func = decorator(func). Decorators are functions that take a function and return a modified function.
Q: Write a simple decorator.
import functools
def log_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__}")
return func(*args, **kwargs)
return wrapper
Exception Handling
Q: except Exception vs bare except?
except Exception catches most errors but not SystemExit or KeyboardInterrupt. Bare except: catches everything — avoid it.
Q: What does raise ... from e do?
Exception chaining — preserves the original traceback when wrapping exceptions.
Quick-Fire Questions
| Question | Answer |
|---|---|
| Is Python compiled or interpreted? | Both — compiled to bytecode, interpreted by VM |
What is __init__ vs __new__? |
__new__ creates object; __init__ initializes it |
| What is a dict comprehension? | {k: v for k, v in iterable} |
What is __name__ == "__main__"? |
True when file run directly |
| What is duck typing? | “If it walks like a duck…” — type by behavior |
| What is a namespace? | Mapping of names to objects (LEGB rule) |
| List vs set for membership? | Set is O(1), list is O(n) |
What is is vs ==? |
is checks identity; == checks equality |