Python Interview Questions on Functions and Scope
Reviewed by Mark Dickie · Last updated
4 questions on this page you can answer and see marked on the spot. Go to the first one
Python functions are reusable blocks defined with def, and each call gets its own local namespace. Interviewers use this topic to test whether you can predict which object a name refers to at runtime, not just whether you can write a function. Most questions come down to the LEGB lookup order, when an assignment creates a local variable, and when default argument values are evaluated. Be ready to explain closures and the difference between global and nonlocal.
What do Python interviewers check about functions and scope?
The table maps each concept to what you should be able to explain and the mistake interviewers listen for.
| Concept | What to explain | Common mistake |
|---|---|---|
| LEGB lookup | Names resolve through local, enclosing, global, then built-in scopes, in that order | Assuming a function sees a module variable that the caller rebinds later |
| Assignment makes a local | Any assignment in a function body makes that name local for the whole body | Reading a global, then assigning to it in the same function, raises UnboundLocalError |
| global and nonlocal | global rebinds a module-level name; nonlocal rebinds a name in the nearest enclosing function | Forgetting nonlocal in a nested function, so the assignment silently creates a new local |
| Mutable default arguments | Default values are evaluated once, when def runs | def add(item, bucket=[]) shares one list across every call that omits bucket |
| Closures in loops | An inner function captures the variable, not the value it had when the function was created | Lambdas built in a for loop all return the value from the final iteration |
How should you practice function scope before the interview?
- Write a function that reads a global, then assigns to the same name, and trigger the UnboundLocalError yourself.
- Build a counter with a closure that uses nonlocal, then rewrite it as a class to compare the two.
- Call a function with a default list three times and print id() of the default to see the shared object.
- Build a list of lambdas in a for loop, then fix the late binding with a default argument.
- Print locals() and globals() inside nested functions and trace each name through the LEGB order.
Interviewers often ask you to explain why the output happened, so keep the traces you ran and the reason for each one.
Key facts
- Tarmac has 51 Python interview questions on this topic, 10 of them on this page, at difficulty 1–4 of 5.
- Tarmac tracked 3,741 job postings asking for Python in November 2026.
- Roles asking for Python advertise a median base salary of £75,000, across 1,641 job postings as of November 2026.
- Tarmac last reviewed these Python interview questions on 30 November 2026.
At a glance
| Questions | 10 shown · 51 in the bank |
|---|---|
| Difficulty | 1–4 of 5 |
| Formats | True / false, Flashcard, Find the bug, Short answer, Ordering, Coding exercise, Multiple choice, Code output |
| Interactive | 2 run your code against tests, in the app |
What you'll review
- comprehensions
- mutable default args
- decorators
- functools hof
- legb scope
Practice questions
Try one before you open the answer. Pick an option and press Check; it's marked on the spot.
In Python 3, the loop variable of a list comprehension leaks into the enclosing scope, overwriting a same-named outer variable.#
Options
Show answer
False. In Python 3 a list comprehension runs in its own implicit scope, so its loop variable does not leak and an outer x keeps its value after [x for x in range(3)]. This leaking behaviour was true in Python 2, where comprehensions shared the surrounding scope, but it was deliberately fixed.
In Python 3 a comprehension runs in its own implicit scope, so its loop variable does not leak — an outer x keeps its value after [x for x in range(3)]. This was true in Python 2, where comprehensions shared the surrounding scope, but it was deliberately fixed.
Where does Python store a function's default argument values, and how can you look at them?#
Show answer
Python evaluates default values once, when the def statement runs, and stores them on the function object in func.__defaults__ (a tuple). Keyword-only defaults go in func.__kwdefaults__ (a dict). Every call that leaves out the argument reuses that same stored object, which is why a mutable default like [] keeps its changes between calls. For example, after def f(x=[]): x.append(1) runs and f() is called twice, f.__defaults__ is ([1, 1],).
The bank doesn't yet cover where default values actually live. Defaults are evaluated once and kept on the function object in __defaults__ and __kwdefaults__. Each call shares those same objects, so a mutable default carries its changes into later calls. You can check this by printing f.__defaults__ after calling the function.
add_item('b') should return ['b'], but the second call returns ['a', 'b']. Which line is the bug?#
def add_item(item, bucket=[]):
bucket.append(item)
return bucket
first = add_item('a')
second = add_item('b')
print(second) # ['a', 'b']Show answer
The bug is on line 1.
Default arguments are evaluated once, at function-definition time, so every call shares the same list object. Mutating it leaks state across calls. Use a sentinel: def add_item(item, bucket=None): then if bucket is None: bucket = [].
What is a decorator, and what does @decorator syntax desugar to?#
Show answer
A decorator is a callable that takes a function (or class) and returns a replacement, used to wrap behaviour like logging, caching, or access checks without editing the original body. @deco above def f(): ... desugars to f = deco(f) — the name is rebound to whatever the decorator returns. A well-behaved wrapper uses functools.wraps to preserve the original's name and docstring.
@deco is sugar for f = deco(f): the decorator receives the function and returns its replacement. This is how cross-cutting concerns (timing, memoisation, auth) are layered on; functools.wraps keeps the wrapped function's metadata intact.
Three decorators are stacked on a function:#
Put these in order
Show answer
Python applies the decorators bottom-up, in this order:
gamma— innermost decorator, closest todefbeta— middle decoratoralpha— outermost decorator, closest to the call site
The stack desugars to fn = alpha(beta(gamma(fn))), so gamma wraps the raw function first and alpha wraps last. At call time the order reverses, but application itself is strictly inside-out.
Python desugars the stack to fn = alpha(beta(gamma(fn))). Application is bottom-up: gamma wraps the raw function first, beta wraps the result of that, and alpha wraps last. At call time the order reverses — alpha's wrapper runs first, then beta's, then gamma's — but the question asks about application, which is strictly inside-out.
Implement run_compose(ops, value): compose a sequence of single-argument operations right-to-left and apply to value. ops is a list of names from {"inc" (+1), "double" (*2), "neg" (negate)}. run_compose(["inc","double"], 3) applies double first then inc → inc(double(3)) = 7. An empty ops list is the identity, returning value unchanged. Build the composition with a real compose(*funcs) helper using functools.reduce.#
Starter code
def run_compose(ops, value):
# TODO: compose the named ops right-to-left, then apply to value
fns = {"inc": lambda x: x + 1, "double": lambda x: x * 2, "neg": lambda x: -x}
result = value
for name in ops:
result = fns[name](result)
return resultYour solution must pass
- double then inc
- three ops right-to-left
This one is written and run, not read. Solve it in the app and your code is executed against these tests and the hidden ones.
What does the second call return?#
Options
Show answer
The second call returns [1, 2]. A default argument is evaluated only once, when the function is defined, so every call that omits acc shares the same list. The first call appends 1 and the second appends 2 to that same list. The fix is to default acc=None and create a fresh list inside the function.
A default argument is evaluated once, when the function is defined, so all calls that omit acc share the same list. The first call appends 1, the second appends 2 to that same list, giving [1, 2]. The fix is acc=None plus if acc is None: acc = [].
What does this print, one value per line?#
def append_to(x, lst=[]):
lst.append(x)
return lst
print(append_to(1))
print(append_to(2))
print(append_to(3))Show answer
[1]
[1, 2]
[1, 2, 3]
The default lst=[] is created once at definition time, so every call that omits lst shares that single list. Each call appends to the accumulating list, producing [1], then [1, 2], then [1, 2, 3] — the classic mutable-default-argument bug. Use lst=None and create a fresh list inside the body to fix it.
This is meant to build functions that return 0, 1, 2, but every call returns 2. What fixes it?#
funcs = []
for i in range(3):
funcs.append(lambda: i)
print([f() for f in funcs]) # want [0, 1, 2]Options
Show answer
Capture the current value as a default: lambda i=i: i
Closures capture the variable i by reference, not its value; after the loop i is 2, so every lambda sees 2. Binding a default argument lambda i=i: i snapshots the value at each iteration.
Implement fib(n) with fib(0)=0, fib(1)=1, fast enough for n=70 within the time limit. Naive double recursion is ~2⁷⁰ calls and times out — memoise with functools.lru_cache, or iterate.#
Starter code
def fib(n):
# TODO: this naive version times out long before n = 70
if n <= 1:
return n
return fib(n - 1) + fib(n - 2)Your solution must pass
- base case zero
- fib(10)
- fib(40) — naive recursion already crawls here
- fib(70) — must beat exponential
This one is written and run, not read. Solve it in the app and your code is executed against these tests and the hidden ones.
Sources
The official documentation these questions are checked against:
Related interview questions
Job market
See python salaries and hiring demand from live job postings.
The other 41 questions
This page shows 10 and marks what you pick. That's as far as a page can go. A free account opens the other 41 and keeps every answer. What you miss comes back until it's right: after a day, then at longer gaps.
Free · the whole bank · 100 answers per 30 days, each marked with written feedback