Interview questions with answers
Python interview questions and answers
Data model, generators, decorators, async, typing and the GIL. Open any question to read its model answer; the multiple-choice set marks the right option and explains it.
- Subjective
- 30
- Objective
- 30
Subjective questions 30
1Lists vs. tuples vs. sets vs. dictionaries: when do you use each?Asked almost every time
Lists are ordered, mutable sequences for collections you change. Tuples are ordered and immutable, for fixed records and dictionary keys. Sets hold unique, hashable items with fast membership tests and set algebra. Dictionaries map keys to values with average O(1) lookup and keep insertion order (Python 3.7+).
2What are decorators and how do they work?Asked almost every time
A decorator is a callable that takes a function and returns a new one, applied with @name above the definition. It wraps behaviour such as logging, caching, retries or access checks around the original. Use functools.wraps so the wrapper keeps the original name and docstring. Decorators with arguments are factories that return the decorator.
3Explain generators and yield.Asked almost every time
A function with yield returns a generator, an iterator that produces values lazily, pausing at each yield and resuming on the next next(). It uses constant memory for long or infinite sequences, such as reading a large file line by line. Generator expressions (x*x for x in data) are the lazy form of list comprehensions.
4What is the GIL and how does it affect concurrency?Asked almost every time
CPython's Global Interpreter Lock lets only one thread run Python bytecode at a time, so threads do not speed up CPU-bound work but are fine for I/O-bound work, because the lock is released while waiting. Use multiprocessing or native extensions for CPU-bound work, and asyncio for many concurrent I/O tasks. Python 3.13+ also offers an experimental free-threaded build without the GIL.
5What are list, dict and set comprehensions, and when should you avoid them?Asked almost every time
Compact expressions that build collections: [x*x for x in nums if x > 0], {k: v for k, v in pairs}, {w.lower() for w in words}. They are faster and clearer than loops for simple transforms, but avoid nesting them deeply or using them for side effects; use a regular loop for readability.
6How does exception handling work in Python?Asked almost every time
try runs code; except SomeError as e handles specific errors; else runs if nothing failed; finally always runs for cleanup. Catch specific exceptions, re-raise with raise or chain with raise NewError() from e, and define custom exceptions by subclassing Exception.
7What are iterators and the iterator protocol?Asked almost every time
An iterable has __iter__ returning an iterator; an iterator has __next__ that returns the next item or raises StopIteration. for loops, comprehensions and many built-ins use this protocol, and generators implement it automatically.
8Threads vs. processes vs. asyncio: when do you use each?Asked almost every time
Use asyncio for many concurrent I/O tasks with async libraries; threads for I/O with blocking libraries; processes (multiprocessing, ProcessPoolExecutor) for CPU-bound work, since the GIL lets only one thread run Python bytecode at a time. Free-threaded builds in 3.13+ are changing this.
9How does asyncio work?Very often asked
An event loop runs coroutines defined with async def. await pauses a coroutine until an awaitable (a network call, asyncio.sleep) completes, letting other coroutines run meanwhile. asyncio.gather or TaskGroup runs tasks concurrently. It is single-threaded cooperative multitasking, ideal for many network connections; blocking calls must be avoided or run in a thread.
10Mutable default arguments: what is the bug?Very often asked
Default values are evaluated once, when the function is defined. def add(item, items=[]) shares one list across calls, so items accumulate. Use items=None and create a new list inside the function.
11Shallow copy vs. deep copy?Very often asked
A shallow copy (list(x), x.copy(), copy.copy) creates a new outer container that still references the same inner objects. A deep copy (copy.deepcopy) recursively copies everything, so nested changes do not affect the original.
12What are context managers?Very often asked
Objects used with with that set something up and guarantee clean-up, even on errors, through __enter__ and __exit__: files, locks, database transactions. contextlib.contextmanager lets you write one as a generator with a single yield.
13How do type hints help, and are they enforced?Very often asked
Hints such as def total(prices: list[float]) -> float document intent, power editor completion and let static checkers (mypy, Pyright) catch bugs before running. Python does not enforce them at runtime; libraries such as Pydantic can validate data against them.
14What are @staticmethod, @classmethod and instance methods?Very often asked
Instance methods take self and work with one object. Class methods take cls and are often alternative constructors (from_json). Static methods take neither; they are plain functions grouped in the class namespace.
15What is a property and why use it?Very often asked
@property turns a method into an attribute-like getter, with optional setter and deleter. It lets you add validation or computed values later without changing how callers access the attribute.
16How does inheritance and MRO work?Very often asked
Classes can inherit from several bases; Python resolves attributes with the method resolution order (C3 linearisation), visible in Class.__mro__. super() calls the next class in the MRO, which makes cooperative multiple inheritance work.
17What are closures and the nonlocal keyword?Very often asked
A closure is an inner function that remembers variables from its enclosing scope even after it returns. To reassign such a variable inside the inner function, declare it nonlocal; otherwise Python treats it as a new local.
18What is __slots__?Very often asked
Declaring __slots__ = ('x', 'y') on a class removes the per-instance __dict__, saving memory and making attribute access slightly faster, at the cost of not being able to add new attributes dynamically.
19How do you write tests in Python?Very often asked
Use pytest: plain functions with assert, fixtures for setup, parametrize for many cases, monkeypatch or unittest.mock for dependencies, and coverage reports. Keep tests fast and independent.
20What are *args and **kwargs?Often asked
*args collects extra positional arguments into a tuple and **kwargs collects extra keyword arguments into a dictionary. They let functions accept flexible arguments and forward them, which is common in decorators and wrappers.
21Explain __init__, __repr__ and other dunder methods.Often asked
Dunder (double underscore) methods hook into Python's data model: __init__ initialises a new object, __repr__ gives an unambiguous representation, __str__ a readable one, __eq__ and __hash__ define equality and hashing, __len__, __iter__ and __getitem__ make objects behave like containers. Dataclasses generate many of them for you.
22How does Python manage memory?Often asked
Mainly by reference counting: an object is freed when no references remain. A cyclic garbage collector finds groups of objects that reference each other but are unreachable. Small objects come from private memory pools.
23How do you manage dependencies and environments?Often asked
Create an isolated virtual environment per project (python -m venv or tools like uv and Poetry), declare dependencies in pyproject.toml, and lock exact versions for reproducible installs. Never install project packages into the system Python.
24What are dataclasses vs. Pydantic models?Often asked
Dataclasses generate __init__, __repr__ and comparisons for plain data containers without validation. Pydantic models validate and convert input at runtime, serialise to JSON and generate schemas, which suits API boundaries and configuration.
25What is the walrus operator?Often asked
:= assigns and returns a value inside an expression, for example while (line := f.readline()): or if (n := len(items)) > 10:. Use it to avoid repeating a computation, but not at the cost of clarity.
26What are match statements?Often asked
Structural pattern matching (3.10+): match command: with case patterns that can destructure sequences, mappings and class instances, bind variables and add guards. It is more powerful than a simple switch.
27How do you profile and speed up Python code?Often asked
Measure first with cProfile, timeit or py-spy. Then use better algorithms and data structures, built-ins and comprehensions, vectorised NumPy, caching (functools.cache), concurrency for I/O, or move hot loops to compiled code.
28What is the difference between __str__ and __repr__?Often asked
__repr__ is an unambiguous developer representation, ideally valid code to recreate the object; __str__ is a readable user-facing string. print uses __str__, falling back to __repr__.
29What is the difference between is and ==?Sometimes asked
== compares values using __eq__; is checks whether two names point to the same object. Use is only for singletons such as None.
30What are virtual environments and why use them?Sometimes asked
Isolated Python installations per project (python -m venv .venv, or tools like uv and Poetry) so each project has its own dependency versions without conflicts or touching the system Python.
Objective questions 30
1Which type is immutable?Asked almost every time
Why: Tuples cannot be changed after creation.
2What does yield turn a function into?Asked almost every time
Why: Calling it returns a lazy generator.
3The GIL mostly limits…Asked almost every time
Why: Only one thread executes bytecode at a time.
4Which block always runs, error or not?Asked almost every time
Why: Used for cleanup.
5Which is best for CPU-bound work in standard CPython?Asked almost every time
Why: The GIL limits threads for Python code.
6What does __next__ raise when an iterator is exhausted?Asked almost every time
Why: for loops catch it.
7What is printed?Very often asked
def add(x, items=[]):
items.append(x)
return items
print(add(1))
print(add(2))Why: The default list is shared between calls.
8Which keyword defines a coroutine?Very often asked
Why: async def functions return coroutines.
9What does functools.wraps preserve?Very often asked
Why: It copies metadata onto the wrapper.
10Which creates a deep copy?Very often asked
Why: Only deepcopy copies nested objects too.
11Which decorator creates an alternative constructor?Very often asked
Why: It receives cls.
12Which keyword reassigns a variable from an enclosing function?Very often asked
Why: Otherwise a new local is made.
13What does __slots__ mainly save?Very often asked
Why: No per-instance __dict__.
14Which validates data at runtime?Very often asked
Why: Pydantic converts and validates input.
15Which shows a class's method resolution order?Very often asked
Why: C3 linearisation.
16What does [x * 2 for x in range(3)] give?Often asked
Why: range(3) is 0, 1, 2.
17Which method makes an object usable in a with block?Often asked
Why: Context managers implement both.
18**kwargs collects extra arguments into a…Often asked
Why: Keyword arguments become a dictionary.
19Which is the right way to test for None?Often asked
Why: None is a singleton; use identity.
20Average lookup time in a dict is…Often asked
Why: Hash tables give constant average lookup.
21What does := do?Often asked
Why: The walrus operator.
22Which tool profiles function calls?Often asked
Why: Built into the standard library.
23Which pytest feature runs a test with many inputs?Often asked
Why: @pytest.mark.parametrize.
24What does print(obj) call first?Often asked
Why: Falls back to __repr__.
25What does raise NewError() from e do?Often asked
Why: The traceback shows both.
26Which caches function results by arguments?Often asked
Why: Memoisation.
27Which runs several coroutines concurrently?Sometimes asked
Why: gather schedules them together and collects results.
28What does @dataclass generate?Sometimes asked
Why: Dataclasses write boilerplate methods from field annotations.
29Which version introduced match statements?Sometimes asked
Why: Structural pattern matching.
30Which command creates a virtual environment?Sometimes asked
Why: Isolates dependencies.
Track what you have practised and search every bank in your dashboard.
Start learning