Python interview questions
Practice Python interview questions on data types, functions and decorators, classes, generators, the GIL, asyncio and memory, with clear answers and code.
21 questions with answers
Showing 21 questions
Data types4 questions
What is the difference between a list and a tuple?Junior
Both are ordered sequences that can hold any objects. You can append to a list, sort it in place or replace an item. Once a tuple is created, its items can't be added, removed or reassigned.
Because a tuple can't change, it is hashable when all its items are hashable, so it can be a dictionary key or a set member:
{(48.85, 2.35): "Paris"}. A list can't. Tuples also use a little less memory and are a natural fit for fixed records, like a function returning(status, body).Pitfall: a tuple is only shallowly immutable.
t = ([1, 2], 3)can't point to a new list, butt[0].append(3)still changes the list inside it, and that tuple is no longer hashable.point = (3, 4) point[0] = 5 # TypeError: 'tuple' object does not support item assignment scores = [70, 85] scores.append(90) # fine: lists are mutable locations = {(48.85, 2.35): "Paris"} # tuple as a key: fine locations = {[48.85, 2.35]: "Paris"} # TypeError: unhashable type: 'list'What is the difference between
isand==?Junior==calls the__eq__method, so two different lists with the same items are equal.iscompares identity: it is true only when both sides are the same object, which you can see withid().Use
isfor singletons:if value is None. For everything else, compare with==.Pitfall:
a is bcan look like it works for small numbers or short strings, because CPython reuses some objects (integers from -5 to 256, for example). That is an implementation detail; code that relies on it breaks with other values.a = [1, 2, 3] b = [1, 2, 3] c = a a == b # True: same values a is b # False: two different list objects a is c # True: c is another name for the same list if result is None: # the right way to check for None ...What is the difference between a shallow copy and a deep copy?Mid-level
Assignment (
b = a) copies nothing: both names point to the same object.list(a),a[:],a.copy()andcopy.copy(a)make a shallow copy: a new list whose items are the same objects as before.That is enough for a list of numbers or strings, which are immutable. With nested mutable objects, changing an inner list through the copy also changes the original.
copy.deepcopy(a)walks the whole structure and copies every level.Rule of thumb: copy shallowly by default and reach for
deepcopyonly for nested mutable data you really need to change independently, since it is slower and copies everything it reaches.import copy grid = [[0, 0], [0, 0]] shallow = grid.copy() deep = copy.deepcopy(grid) shallow[0][0] = 1 print(grid) # [[1, 0], [0, 0]] the inner list is shared print(deep) # [[0, 0], [0, 0]] fully independentHow does a dictionary work, and what can be a key?Mid-level
When you store
d[key] = value, Python callshash(key)and uses the result to pick a slot. When two keys land in the same slot, it compares them with==to find the right one. That is why lookups, inserts and deletes are O(1) on average, compared with O(n) for searching a list.A key must keep the same hash for its whole life, so strings, numbers, tuples of hashable items and frozen sets work, but lists, dicts and sets don't. Your own classes are hashable by identity, unless you define
__eq__, in which case you must also define__hash__from the same fields.Since Python 3.7, dictionaries keep insertion order as part of the language. Use
dict.get(key, default)orcollections.defaultdictinstead of catchingKeyErroreverywhere.from collections import defaultdict words = ["apple", "avocado", "banana"] by_letter = defaultdict(list) for word in words: by_letter[word[0]].append(word) print(dict(by_letter)) # {'a': ['apple', 'avocado'], 'b': ['banana']} print(by_letter.get("z", [])) # [] without a KeyError
Functions4 questions
What do
*argsand**kwargsmean?JuniorThey let a function accept any number of arguments. Inside the function,
argsis a tuple andkwargsis a dictionary. You often see them in wrappers and decorators that pass every argument through to another function.The same stars unpack when you call a function:
f(*items)spreads a list into positional arguments andf(**options)spreads a dict into keyword arguments.A bare
*in a signature makes the parameters after it keyword-only, likedef connect(host, *, timeout=5). That keeps calls readable (connect("db", timeout=10)) and lets you add options later without breaking callers.def log(message, *args, **kwargs): print(message, args, kwargs) log("saved", 1, 2, user="ana") # saved (1, 2) {'user': 'ana'} values = [3, 1, 2] print(max(*values)) # 3, same as max(3, 1, 2)Why is a mutable default argument a bug?Mid-level
Python creates the default object a single time, when it runs the
defline, and stores it on the function. Every call that doesn't pass the argument gets that same object. If the function changes it, the next call sees the change.The fix is to use
Noneas the default and create a fresh object inside the function. Linters like Ruff and Pylint warn about this pattern.The same rule explains why
def f(now=datetime.now())always returns the time the module was loaded, not the time of the call.# Bug: the list is shared between calls def add_item(item, cart=[]): cart.append(item) return cart add_item("apple") # ['apple'] add_item("pear") # ['apple', 'pear'] surprise # Fix: create a new list on each call def add_item(item, cart=None): if cart is None: cart = [] cart.append(item) return cartWhat is a decorator, and how would you write one?Mid-level
Functions are objects in Python, so you can pass them to other functions and return them. A decorator uses that: it defines an inner
wrapperthat does something before or after calling the original, then returns the wrapper.Always use
functools.wrapson the wrapper. Without it, the decorated function loses its name and docstring, which confuses logs, debuggers and tools like pytest.Common real uses: timing, logging, retries, caching (
functools.lru_cache), access checks in web frameworks (@app.get("/"),@login_required).import functools import time def timer(func): @functools.wraps(func) def wrapper(*args, **kwargs): start = time.perf_counter() result = func(*args, **kwargs) print(f"{func.__name__} took {time.perf_counter() - start:.3f}s") return result return wrapper @timer def slow_sum(n): return sum(range(n)) slow_sum(10_000_000) # prints e.g. "slow_sum took 0.180s"How does variable scope work in Python, and what is a closure?Mid-level
When you use a name, Python searches the current function, then any enclosing functions, then the module, then the built-ins. Assigning to a name inside a function makes it local, unless you declare it
globalornonlocal.A closure keeps a reference to the enclosing variables, not a copy of their values. That is what makes counters and decorators work.
Classic pitfall: lambdas created in a loop all see the loop variable's final value, because they look it up when they run, not when they are created. Bind the current value with a default argument.
def make_counter(): count = 0 def increment(): nonlocal count count += 1 return count return increment counter = make_counter() counter(); counter() # 1, then 2 # Late binding pitfall funcs = [lambda: i for i in range(3)] print([f() for f in funcs]) # [2, 2, 2] funcs = [lambda i=i: i for i in range(3)] print([f() for f in funcs]) # [0, 1, 2]
Classes4 questions
What is the difference between an instance method, a class method and a static method?Junior
Instance methods are the default and work with one object's data.
@classmethodmethods receive the class, so they are the usual way to write alternative constructors likeDate.from_string("2026-12-05"), and they still work correctly in subclasses.@staticmethodmethods receive nothing automatically. Use one for a helper that belongs with the class but doesn't need its state; often a module-level function is just as good.class Temperature: def __init__(self, celsius): self.celsius = celsius def fahrenheit(self): # instance method return self.celsius * 9 / 5 + 32 @classmethod def from_fahrenheit(cls, f): # alternative constructor return cls((f - 32) * 5 / 9) @staticmethod def is_freezing(celsius): # no self, no cls return celsius <= 0 t = Temperature.from_fahrenheit(212) print(t.celsius) # 100.0What are dunder methods, and what is the difference between
__repr__and__str__?Junior"Dunder" means double underscore. Python calls these methods for you:
len(x)callsx.__len__(),a == bcallsa.__eq__(b),for item in xcallsx.__iter__(). Defining them makes your objects behave like built-in types.repr(obj)is what you see in the REPL, in lists and in logs; ideally it looks like code that would recreate the object.str(obj)andprint(obj)use__str__, and fall back to__repr__if there is no__str__.Practical rule: always define
__repr__, it makes debugging much easier. Add__str__only when users need a different, friendlier text.class Money: def __init__(self, amount, currency): self.amount = amount self.currency = currency def __repr__(self): return f"Money({self.amount!r}, {self.currency!r})" def __str__(self): return f"{self.amount:.2f} {self.currency}" price = Money(9.5, "EUR") print([price]) # [Money(9.5, 'EUR')] print(price) # 9.50 EURWhat does
@dataclassgive you, and when would you use it?Mid-levelWithout it, a simple record class needs the same field names typed three or four times. With
@dataclass, you list the fields with type hints and Python generates the boilerplate.Useful options:
frozen=Truemakes instances immutable and hashable,order=Trueadds comparison methods,slots=True(Python 3.10+) uses less memory. For a mutable default, usefield(default_factory=list); a plain= []raises an error for exactly the reason mutable defaults are dangerous.If you need validation and parsing of outside data, like JSON from an API, a library such as Pydantic is a better fit; dataclasses don't check types at runtime.
from dataclasses import dataclass, field @dataclass(frozen=True) class User: name: str email: str roles: tuple[str, ...] = () @dataclass class Cart: items: list[str] = field(default_factory=list) print(User("Ana", "ana@example.com")) # User(name='Ana', email='ana@example.com', roles=())How does multiple inheritance work in Python, and what does
super()really call?SeniorWhen a class has several bases, Python builds one linear order of every class in the hierarchy, visible in
Class.__mro__. Each class appears before its own bases, and the order of bases in the class statement is kept. Method lookup walks that list.super().method()means "the next class after me in the MRO of the actual object". In a diamond (D(B, C)where both inherit fromA),super()inBcallsC, notA. That is what lets cooperative classes each run once, as long as every class callssuper()and accepts**kwargsit doesn't use.In practice, keep multiple inheritance to small mixins that add one behavior, and prefer composition for anything bigger. Deep diamonds are hard to read and easy to break.
class A: def hello(self): return ["A"] class B(A): def hello(self): return ["B"] + super().hello() class C(A): def hello(self): return ["C"] + super().hello() class D(B, C): pass print(D().hello()) # ['B', 'C', 'A'] print([k.__name__ for k in D.__mro__]) # ['D', 'B', 'C', 'A', 'object']
Iterators & context managers3 questions
What is a generator, and why would you use one?Mid-level
Calling a generator function doesn't run it; it returns a generator object. Each
next()(or each step of aforloop) runs the code until the nextyield, hands back that value and pauses. When the function ends, iteration stops.Because values are produced lazily, you can process a 10 GB log file line by line, or an infinite sequence, without loading everything into memory. Generators also chain well into pipelines.
Pitfall: a generator can be consumed only once. A second loop over the same generator gets nothing; create a new one or store the results in a list if you need them twice.
def read_errors(path): with open(path) as file: for line in file: if "ERROR" in line: yield line.rstrip() errors = read_errors("app.log") # nothing is read yet for line in errors: # reads one line at a time print(line) squares = (n * n for n in range(1_000_000)) # generator expression print(sum(squares))What is the difference between a list comprehension and a generator expression?Junior
Use a list comprehension when you need the results more than once, need their length, or need to index into them. Use a generator expression when you consume the items once, especially when passing them straight to
sum,any,maxor"".join.With a million items, the list comprehension holds a million objects at once; the generator holds one at a time.
any(...)with a generator can also stop early, as soon as it finds a match.Readability matters too: if a comprehension needs more than one
forand anif, a normal loop is usually clearer.numbers = range(1_000_000) evens = [n for n in numbers if n % 2 == 0] # a list of 500,000 ints total = sum(n for n in numbers if n % 2 == 0) # no list built has_negative = any(n < 0 for n in numbers) # stops at the first match lengths = {word: len(word) for word in ["hi", "hello"]} # dict comprehensionWhat does the
withstatement do, and how do you write your own context manager?Mid-levelwith open(path) as f:guarantees the file is closed when the block ends, whatever happens inside. The same pattern releases locks, commits or rolls back database transactions, and restores temporary settings.A class becomes a context manager by defining
__enter__(its return value is bound byas) and__exit__, which receives the exception, if any. ReturningTruefrom__exit__swallows the exception, which you rarely want.For simple cases,
contextlib.contextmanagerturns a generator into a context manager: code beforeyieldis setup, code after it is cleanup. Put the cleanup in afinallyso it runs on errors too.from contextlib import contextmanager import time @contextmanager def timed(label): start = time.perf_counter() try: yield finally: print(f"{label}: {time.perf_counter() - start:.2f}s") with timed("import"): load_users() # prints the time even if load_users() raises
Memory & concurrency3 questions
How does Python manage memory?Mid-level
Every object has a reference count. Assigning it to a name, putting it in a list or passing it to a function adds a reference; when names go out of scope or are deleted, the count goes down. At zero, the memory is freed immediately.
Reference counting alone can't free cycles, like two objects that point to each other. The
gcmodule runs a generational collector that finds and frees those unreachable cycles from time to time.Memory leaks in Python are usually objects kept alive on purpose by mistake: a growing module-level cache, a list of callbacks never removed, or a global dict of sessions.
tracemallocshows which lines allocate the most memory.import sys data = [] print(sys.getrefcount(data)) # small number: the name, plus temporary references a = {} b = {"other": a} a["other"] = b # a cycle: only the gc module can free these two del a, bWhat is the GIL, and how does it affect multithreaded code?Senior
The GIL protects CPython's internals, like reference counts, from being corrupted by threads running at the same time. A thread waiting on the network, disk or a database releases it, so threads work well for I/O-bound tasks such as calling many APIs.
For CPU-bound work, like image processing or number crunching in pure Python, threads take turns instead of running in parallel. The usual answers are
multiprocessingorconcurrent.futures.ProcessPoolExecutor(separate processes, each with its own GIL), or libraries like NumPy that do the heavy work in C and release the GIL.This is changing: Python 3.13 added an experimental free-threaded build without the GIL (PEP 703), and Python 3.14 made it officially supported but still optional. The default build still has the GIL, and some C extensions don't support free-threading yet, so check before relying on it.
When would you choose threading, multiprocessing or asyncio?Senior
asyncioruns one thread with an event loop. Tasks give up control at eachawait, so thousands of connections can wait at the same time with little overhead. It needs async libraries all the way down (httpx,asyncpg); one blocking call, liketime.sleeporrequests.get, freezes every task.Threads (
ThreadPoolExecutor) work with ordinary blocking libraries and are the simplest way to run, say, 20 downloads at once. Because of the GIL they don't speed up CPU work, and shared data needs locks.Processes (
ProcessPoolExecutor) run on all CPU cores, but starting them costs more and arguments must be pickled to cross between processes. In an interview, say which kind of bottleneck you have first, I/O or CPU, then pick.import asyncio import httpx async def fetch_all(urls): async with httpx.AsyncClient() as client: responses = await asyncio.gather(*(client.get(url) for url in urls)) return [r.status_code for r in responses] # CPU-bound work: use processes instead from concurrent.futures import ProcessPoolExecutor with ProcessPoolExecutor() as pool: results = list(pool.map(resize_image, paths))
Tooling & performance3 questions
What is a virtual environment, and why should you use one?Junior
Without one, every
pip installgoes into the same global location, and two projects that need different versions of Django or NumPy break each other. A virtual environment isolates them.Create one with
python -m venv .venv, activate it, then install packages. Record the dependencies inpyproject.toml(orrequirements.txt) and pin exact versions with a lock file, so teammates and servers install the same thing. Tools like uv and Poetry manage the environment and the lock file for you.Don't commit the
.venvfolder; commit the dependency files and recreate the environment from them.python -m venv .venv source .venv/bin/activate # Windows: .venv\Scripts\activate pip install requests pip freeze > requirements.txt # or, with uv uv init uv add requestsAre type hints enforced at runtime?Mid-level
def total(prices: list[float]) -> floatdocuments the expected types, but callingtotal("abc")still runs until something actually fails. The hints are stored in__annotations__and otherwise do nothing by themselves.Their value comes from tools: a type checker in CI catches wrong argument types, missing
Nonechecks and typos in attribute names before the code runs, and makes large refactors much safer.Some libraries do read hints at runtime on purpose: Pydantic and FastAPI use them to validate and convert incoming data. That is the library's work, not Python's.
def average(values: list[float]) -> float | None: if not values: return None return sum(values) / len(values) average("abc") # runs, then fails inside sum(): TypeError # mypy reports it before running: # error: Argument 1 to "average" has incompatible type "str"A Python function is too slow. How do you make it faster?Senior
Guessing is usually wrong. Run
cProfile(or a sampling profiler like py-spy on a live process) to see where the time goes, andtimeitto compare two versions of a small piece.The biggest wins are usually algorithmic: checking membership in a
setinstead of a list turns O(n) into O(1), and a dict lookup can replace a nested loop. Next, avoid repeated work withfunctools.lru_cache, and move tight loops into built-ins (sum,sorted), comprehensions or vectorized NumPy and pandas operations, which run in C.Only after that, consider parallelism (processes for CPU work, asyncio or threads for I/O) or compiled options like Cython or a Rust extension. Recent Python versions are also noticeably faster, so upgrading can be a cheap win.
# Slow: "in" on a list scans every item, O(n * m) banned = load_banned_ids() # list of 100,000 ids clean = [u for u in users if u.id not in banned] # Fast: a set lookup is O(1) on average banned = set(load_banned_ids()) clean = [u for u in users if u.id not in banned] # Find the hot spot first # python -m cProfile -s cumtime app.py
Found these questions useful?
New articles, quizzes and tools in your inbox, about once a month. No spam, and you can unsubscribe at any time.
Comments
Join the discussion
Comments are provided by Disqus. Showing them connects to Disqus, which may set cookies. See our privacy policy.
