Interview Q&A · Python · 25 questions in this topic
Functions — Python Interview Q&A
Defining and calling functions, the parameter rules interviewers probe, closures, recursion and the functional tools in the standard library. Part of Functions · 375 questions in the Python bank.
How do you define a function in Python?
Answer
Functions are defined with the def keyword, a name, a parenthesized parameter list, and an indented body. A function returns None implicitly if it has no explicit return statement.
Unlike some languages, Python doesn't require declaring a return type, and a function can return different types from different code paths (since Python is dynamically typed). A return with no value, or falling off the end of the function without hitting return at all, both produce None.
Example
def add(a, b): return a + b def log_message(msg): print(msg) # no explicit return -> returns None result = log_message("hello") print(result) # None
💡 Mentioning that "a function with no return returns None " unprompted is a small detail that separates careful answers from rushed ones — it comes up constantly when debugging unexpected None values.
What is the difference between parameters and arguments?
Answer
A parameter is the name listed in a function's definition; an argument is the actual value passed in when the function is called. The terms are often used interchangeably in casual conversation, but interviewers sometimes probe the distinction directly.
Think of parameters as the placeholders a function declares it needs, and arguments as what you actually hand it at the call site.
Example
def greet(name, greeting="Hello"): # name, greeting -> parameters return f"{greeting}, {name}!" print(greet("Ana", "Hi")) # "Ana", "Hi" -> arguments
💡 A quick, precise answer here ("parameters are declared, arguments are passed") signals attention to terminology that experienced interviewers notice.
What are positional arguments, and how does their order matter?
Answer
Positional arguments are matched to parameters strictly by their order in the function call — the first argument fills the first parameter, the second fills the second, and so on.
Getting the order wrong doesn't raise an error if the types happen to be compatible — it just silently produces the wrong result, which makes positional-argument mistakes a common source of subtle bugs, especially with several same-typed parameters in a row.
Example
def describe_pet(name, species): return f"{name} is a {species}" print(describe_pet("Rex", "dog")) # 'Rex is a dog' -- correct order print(describe_pet("dog", "Rex")) # 'dog is a Rex' -- swapped! no error, just wrong
What are keyword arguments, and why are they useful?
Answer
Keyword arguments are passed as name=value at the call site, matched to parameters by name rather than position. This makes calls more explicit and order-independent, and is especially valuable for functions with several optional parameters.
Keyword arguments can be supplied in any order (as long as they come after any positional arguments), and they make call sites self-documenting — the reader doesn't need to check the function signature to know what each value means.
Example
def create_user(name, age, active=True, role="member"): return {"name": name, "age": age, "active": active, "role": role} # Order-independent and self-documenting user = create_user(name="Ana", role="admin", age=30) print(user) # {'name': 'Ana', 'age': 30, 'active': True, 'role': 'admin'}
💡 Bring up readability at scale — "when a function has 4+ parameters, especially several booleans or same-typed values, keyword arguments prevent the classic create_user('Ana', 30, True, False) guessing game at the call site."
What are default arguments in Python?
Answer
A default argument supplies a fallback value used when the caller doesn't provide one for that parameter, defined with param=value in the function signature.
Default values are evaluated once, at function definition time — not on every call. This is exactly why mutable defaults (lists, dicts) are dangerous (see Q61): the same default object is reused across every call that doesn't override it.
Example
def connect(host, port=8080, timeout=30): return f"Connecting to {host}:{port} (timeout={timeout}s)" print(connect("example.com")) # uses both defaults print(connect("example.com", timeout=60)) # overrides just timeout
💡 "Defaults are evaluated once, at definition time" is the single most important sentence to say correctly here — it's the seed for the very next (and much more commonly asked) question.
Why is using a mutable default argument dangerous in Python?
Answer
Because default argument values are created exactly once, at function definition time, a mutable default (like [] or {}) is shared across every call that doesn't explicitly pass its own value — mutations from one call leak into the next.
This is one of the most infamous Python gotchas, and interviewers ask it specifically to see if a candidate has been burned by it in real code. The fix is to use None as the default and create the actual mutable object inside the function body on each call.
Example
def add_item(item, basket=[]): # BUG: basket is created once, at def time basket.append(item) return basket print(add_item("apple")) # ['apple'] print(add_item("banana")) # ['apple', 'banana'] -- unexpected! same list reused # Correct fix: def add_item_fixed(item, basket=None): if basket is None: basket = [] # fresh list created every call basket.append(item) return basket print(add_item_fixed("apple")) # ['apple'] print(add_item_fixed("banana")) # ['banana'] -- correct, independent call
What is *args, and when would you use it?
Answer
*args collects any number of extra positional arguments into a tuple inside the function, letting you write functions that accept a variable number of positional inputs.
args is just a conventional name — the meaningful part is the *, which tells Python "gather all remaining positional arguments here." This is how built-ins like print() accept an arbitrary number of values.
Example
def total(*args): print(type(args)) # <class 'tuple'> return sum(args) print(total(1, 2, 3)) # 6 print(total(10, 20, 30, 40))# 100 def describe(first, *rest): print("First:", first) print("Rest:", rest) describe("a", "b", "c") # First: a Rest: ('b', 'c')
💡 Point out that *args is positional collection specifically — pair it with **kwargs (Q63) to show you understand both halves of Python's variadic argument system.
What is **kwargs, and when would you use it?
Answer
**kwargs collects any number of extra keyword arguments into a dictionary, letting a function accept arbitrary named parameters it doesn't explicitly declare.
This is commonly used for configuration-style functions, wrapper/decorator functions that need to forward arbitrary arguments to another function, and APIs designed to be extended without breaking existing call sites.
Example
def build_profile(**kwargs): print(type(kwargs)) # <class 'dict'> return kwargs profile = build_profile(name="Ana", age=30, city="Lisbon") print(profile) # {'name': 'Ana', 'age': 30, 'city': 'Lisbon'} def call_with_logging(func, *args, **kwargs): print(f"Calling {func.__name__} with {args}, {kwargs}") return func(*args, **kwargs)
💡 The "forwarding" pattern — def wrapper(*args, **kwargs): return original(*args, **kwargs) — is exactly what decorators rely on. Mentioning that connection here previews depth you'll demonstrate later.
What order must function parameters be declared in?
Answer
The required order is: standard positional parameters, then *args, then keyword-only parameters, then **kwargs. Violating this order is a SyntaxError, not just a style issue.
Since Python 3.8, you can also mark parameters as strictly positional-only (before a /) or strictly keyword-only (after a bare *), giving fine-grained control over how a function may be called.
Example
def full_signature(a, b, /, c, d=10, *args, e, f=20, **kwargs): pass # positional-only: a, b | regular: c, d | *args | # keyword-only: e, f | **kwargs def example(pos_only, /, standard, *args, kw_only, **kwargs): print(pos_only, standard, args, kw_only, kwargs) example(1, 2, 3, 4, kw_only="required", extra="allowed") # pos_only=1, standard=2, args=(3, 4), kw_only='required', kwargs={'extra': 'allowed'}
💡 Being able to correctly order a signature combining /, *args, keyword-only params, and **kwargs from memory is a strong senior-level signal — most candidates only know the basics.
What are first-class functions in Python?
Answer
"First-class functions" means functions are treated like any other value in the language — they can be assigned to variables, stored in data structures, passed as arguments, and returned from other functions.
This is a foundational property that makes higher-order functions, decorators, and callback-based APIs possible in Python. A function is just an object of type function, like an int is an object of type int.
Example
def shout(text): return text.upper() + "!" # Assigned to a variable greet_loudly = shout print(greet_loudly("hello")) # 'HELLO!' # Stored in a data structure operations = {"shout": shout, "len": len} print(operations["shout"]("hi")) # 'HI!' # Passed as an argument def apply(func, value): return func(value) print(apply(shout, "test")) # 'TEST!'
💡 Ground the abstract definition in one concrete consequence: "because functions are first-class, I can pass str.upper directly into map() instead of writing a wrapper lambda."
What are higher-order functions?
Answer
A higher-order function either takes one or more functions as arguments, returns a function, or both. map(), filter(), sorted(key=.), and decorators are all higher-order functions.
Higher-order functions are only possible because functions are first-class citizens (Q65) — you can't pass a function as an argument in a language where functions aren't values.
Example
def make_multiplier(factor): # returns a function -> higher-order def multiplier(x): return x * factor return multiplier double = make_multiplier(2) triple = make_multiplier(3) print(double(5), triple(5)) # 10 15 words = ["banana", "kiwi", "fig"] print(sorted(words, key=len)) # takes a function argument -> higher-order
💡 make_multiplier above is also a closure (Q72) — connecting higher-order functions to closures in your answer shows you see how these concepts build on each other rather than existing in isolation.
What are lambda functions, and when should (and shouldn't) you use them?
Answer
A lambda is a small, anonymous, single-expression function: lambda arguments: expression. They're best used for short, throwaway functions passed directly into something like sorted(), map(), or filter() — not for anything complex enough to need a name or multiple statements.
A lambda can only contain a single expression (no statements, no multiple lines, no if / for blocks in the general sense — only conditional expressions). If you find yourself needing a comment to explain a lambda, or assigning it to a variable to reuse it, that's a sign it should be a regular def function instead — PEP 8 explicitly discourages assigning lambdas to names.
Example
# Idiomatic: short, inline, throwaway words = ["banana", "kiwi", "fig"] print(sorted(words, key=lambda w: len(w))) # ['fig', 'kiwi', 'banana'] square = lambda x: x ** 2 # discouraged by PEP 8 -- just use `def square(x): return x ** 2` # A lambda can contain a conditional expression classify = lambda n: "even" if n % 2 == 0 else "odd" print(classify(4)) # 'even'
What does map() do, and how is it used?
Answer
map(function, iterable) applies function to every item of iterable and returns a lazy iterator of the results — you typically wrap it in list() to see the values immediately, or consume it directly in a loop.
map() can also take multiple iterables at once, applying a function that takes multiple arguments across them in parallel, stopping at the shortest iterable.
Example
nums = [1, 2, 3, 4] squared = map(lambda n: n ** 2, nums) print(list(squared)) # [1, 4, 9, 16] -- map() itself is lazy a = [1, 2, 3] b = [10, 20, 30] sums = map(lambda x, y: x + y, a, b) print(list(sums)) # [11, 22, 33] -- pairs elements from both iterables
💡 Mention that map() returns an iterator, not a list, in Python 3 (unlike Python 2) — this is a common trip-up for developers with older Python knowledge or coming from tutorials that predate the change.
What does filter() do, and how is it used?
Answer
filter(function, iterable) returns a lazy iterator containing only the items of iterable for which function returns a truthy value. Passing None as the function filters out all falsy values directly.
Like map(), filter() is lazy — nothing is computed until you iterate over it or convert it with list().
Example
nums = [1, -2, 3, -4, 5, 0] positives = filter(lambda n: n > 0, nums) print(list(positives)) # [1, 3, 5] truthy_only = filter(None, [0, 1, "", "hi", [], [1], False, True]) print(list(truthy_only)) # [1, 'hi', [1], True]
💡 The filter(None, iterable) idiom for stripping out falsy values is a small, memorable trick worth mentioning — it shows you know the special-cased behavior, not just the common case.
What does functools.reduce() do, and how is it used?
Answer
reduce(function, iterable, initializer) cumulatively applies a two-argument function to the items of an iterable, reducing it down to a single value — e.g., summing or multiplying a whole list.
Unlike map() and filter(), reduce() isn't a built-in in Python 3 — it lives in the functools module, reflecting a deliberate decision that explicit loops are usually clearer for this kind of accumulation. It's still useful, but many experienced Python developers reach for a plain loop or a built-in like sum() / max() instead when one exists.
Example
from functools import reduce nums = [1, 2, 3, 4, 5] product = reduce(lambda acc, x: acc * x, nums) print(product) # 120 -- 1*2*3*4*5 total = reduce(lambda acc, x: acc + x, nums, 100) # with an initial value print(total) # 115 -- starts accumulating from 100
💡 If the operation has a dedicated built-in (sum(), max(), min(), any(), all()), use that instead of reduce() — mentioning this shows judgment about when a "clever" tool is actually the wrong tool.
Should you prefer map() / filter() or list comprehensions in modern Python?
Answer
Most style guides and experienced Python developers prefer list comprehensions over map() / filter() with lambdas, because comprehensions read more naturally as Python and don't require wrapping simple logic in a lambda.
map() / filter() still have a place when you already have a named function (not a lambda) to pass in — map(str.upper, words) is arguably as clean as the comprehension equivalent. Performance between the two is roughly comparable in most real-world cases; the deciding factor is usually readability, not speed.
Example
words = ["banana", "kiwi", "fig"] # map + lambda -- workable but slightly indirect upper1 = list(map(lambda w: w.upper(), words)) # List comprehension -- generally considered more Pythonic here upper2 = [w.upper() for w in words] # map with an existing named function -- perfectly clean, arguably even more concise upper3 = list(map(str.upper, words)) print(upper1 == upper2 == upper3) # True
💡 A senior-sounding answer isn't "always use comprehensions" — it's "I reach for a comprehension by default, but map() with an existing named function is just as readable and I'll use whichever reads more clearly in context."
What are closures in Python?
Answer
A closure is a nested function that "remembers" and can access variables from its enclosing function's scope, even after the outer function has finished executing.
For a closure to exist, you need: a nested function, that nested function referencing a variable from the enclosing (not global) scope, and the enclosing function returning the nested function. Python keeps those referenced variables alive in a special "cell" object attached to the returned function, accessible via __closure__.
Example
def make_counter(): count = 0 # enclosing-scope variable def increment(): nonlocal count # needed because we reassign count count += 1 return count return increment # returning the nested function -> closure counter1 = make_counter() counter2 = make_counter() # a completely separate closure, own 'count' print(counter1()) # 1 print(counter1()) # 2 print(counter2()) # 1 -- independent from counter1
💡 "Each call to make_counter() creates a brand-new closure with its own independent count " is the key insight interviewers are checking for — many candidates can define a closure but can't explain why two closures from the same factory function don't interfere with each other.
What is the classic closure "late binding" bug, and how do you fix it?
Answer
When closures are created inside a loop, they don't capture the loop variable's value at creation time — they capture the variable itself, which keeps changing. By the time the closures are called, the loop has finished and every closure sees the loop variable's final value.
The fix is to force early binding by capturing the current value as a default argument (default argument values are evaluated immediately, at definition time — tying back to Q60), or by using a factory function that creates a fresh scope per iteration.
Example
# Buggy: all closures share the same 'i', which ends up being 2 for all of them funcs = [] for i in range(3): funcs.append(lambda: i) print([f() for f in funcs]) # [2, 2, 2] -- not [0, 1, 2] as you might expect! # Fixed: default argument captures the current value of i immediately funcs_fixed = [] for i in range(3): funcs_fixed.append(lambda i=i: i) # i=i binds NOW, not later print([f() for f in funcs_fixed]) # [0, 1, 2] -- correct
What is recursion, and what are its trade-offs in Python?
Answer
Recursion is a function calling itself to solve a smaller instance of the same problem, with a base case that stops the recursion. In Python specifically, recursion has a real practical limit (default ~1000 frames) and no automatic tail-call optimization, so deep recursion can crash with a RecursionError or use significant memory.
Every recursive call adds a new frame to the call stack; Python's default recursion limit (sys.getrecursionlimit(), typically 1000) exists to prevent a runaway recursive function from crashing the interpreter with a stack overflow. For deep or performance-sensitive recursive logic, an iterative rewrite (often using an explicit stack) is usually safer and faster in Python.
Example
import sys def factorial(n): if n <= 1: # base case return 1 return n * factorial(n - 1) # recursive case print(factorial(5)) # 120 print(sys.getrecursionlimit()) # 1000 (default) # factorial(5000) # eventually raises RecursionError: maximum recursion depth exceeded
💡 Always name the two required ingredients explicitly — a base case and a recursive case that moves toward that base case — since forgetting either is the most common cause of infinite recursion.
Does Python optimize tail recursion?
Answer
No. Unlike some functional languages (Scheme, Elixir), CPython does not perform tail-call optimization, even when a recursive call is the very last operation in a function. Every recursive call still adds a new stack frame.
This is a deliberate design decision by Python's creators, not a missing feature — full tracebacks (which rely on the call stack being preserved) were considered more valuable for debugging than the performance/memory benefit of tail-call elimination.
Practically, this means even a "tail-recursive-style" function in Python will still hit the recursion limit on large inputs, unlike the equivalent in a language that does optimize it.
Example
def sum_tail(n, acc=0): if n == 0: return acc return sum_tail(n - 1, acc + n) # "tail position," but Python still doesn't optimize it # sum_tail(10000) # still raises RecursionError -- no TCO in CPython # Practical fix: rewrite iteratively def sum_iterative(n): acc = 0 while n > 0: acc += n n -= 1 return acc print(sum_iterative(10000)) # works fine, no recursion involved
💡 If asked "how would you optimize this recursive function," and tail-call structure is already present, the correct senior answer is "Python won't optimize this automatically — I'd convert it to an explicit loop," not "make it tail-recursive."
What are function annotations and type hints in Python?
Answer
Type hints (via function annotation syntax, def f(x: int) -> str:) let you document expected parameter and return types. They are not enforced at runtime by the interpreter — they exist for readability, IDE support, and static type checkers like mypy or pyright.
Because Python remains dynamically typed, adding a type hint doesn't stop you from passing the "wrong" type — nothing crashes; the hint is purely informational unless you run a separate static-analysis tool against your code. This is a very common point of confusion for developers coming from statically typed languages.
Example
def greet(name: str, age: int = 0) -> str: return f"{name} is {age}" print(greet("Ana", 30)) # 'Ana is 30' -- works normally print(greet(123, "oops")) # ALSO runs without error! hints aren't enforced at runtime print(greet.__annotations__) # {'name': <class 'str'>, 'age': <class 'int'>, 'return': <class 'str'>}
What are docstrings, and what are the common docstring styles?
Answer
A docstring is a string literal placed as the first statement in a function, class, or module, documenting what it does. It's accessible at runtime via.__doc__ or help(). The three common conventions are Google style, NumPy style, and reStructuredText (Sphinx) style.
Docstrings differ from ordinary comments in that they're actual objects Python stores and exposes — documentation tools like Sphinx can extract them automatically to build reference documentation, and IDEs display them as tooltips.
Example
def divide(a: float, b: float) -> float: """Divide a by b. Args: a (float): The numerator. b (float): The denominator. Must not be zero. Returns: float: The result of a / b. Raises: ZeroDivisionError: If b is zero. """ return a / b print(divide.__doc__) help(divide)
💡 Naming a specific docstring style you've used (Google, NumPy, or Sphinx/reST) and why your team chose it is more convincing than describing docstrings in the abstract.
What is a pure function, and why does it matter?
Answer
A pure function always returns the same output for the same input and produces no observable side effects (no mutating external state, no I/O, no modifying its arguments). Pure functions are easier to test, reason about, cache, and run in parallel safely.
Impure functions aren't "wrong" — plenty of necessary code needs side effects (writing to a database, logging, mutating a shared cache) — but isolating the pure, logic-heavy parts of a codebase from the impure, side-effectheavy parts (I/O, state mutation) is a widely recommended design principle that makes testing dramatically simpler.
Example
# Pure: same input always gives same output, no external state touched def add_tax(price, rate): return price * (1 + rate) # Impure: depends on external state (current time) and has a side effect (print) import datetime def log_purchase(item): print(f"{datetime.datetime.now()}: purchased {item}") # side effect return True
💡 If asked "how would you make this function easier to test," identifying which parts are impure (I/ O, global state, randomness, current time) and isolating them from the pure calculation logic is exactly the answer being sought.
What is the difference between a function and a method?
Answer
A method is simply a function that's defined inside a class and bound to instances of that class — it's called on an object (obj.method()) and automatically receives that object as its first argument (self).
Under the hood, a method is still just a function object; Python's descriptor protocol is what automatically binds it to an instance and supplies self when you access it through an object rather than the class directly.
Example
def standalone_function(x): return x * 2 class Doubler: def method(self, x): # self is filled in automatically return x * 2 d = Doubler() print(standalone_function(5)) # 10 -- called directly print(d.method(5)) # 10 -- self=d is passed automatically # Proof that a method is just a function bound to an instance: print(Doubler.method) # <function Doubler.method at ...> print(d.method) # <bound method Doubler.method of <...>>
💡 Showing that Doubler.method (accessed on the class) is a plain function, while d.method (accessed on an instance) is a "bound method," demonstrates real understanding of how Python's attribute lookup and binding actually work — most candidates only know the surface-level distinction.
What is functools.partial, and when would you use it?
Answer
functools.partial creates a new callable with some of a function's arguments already "locked in," letting you specialize a general-purpose function into a more specific one without writing a wrapper by hand.
This is especially useful when passing a function into an API (like map(), a callback registry, or an event handler) that will call it with a fixed number of arguments, but the underlying function needs additional configuration that isn't part of that call signature.
Example
from functools import partial def power(base, exponent): return base ** exponent square = partial(power, exponent=2) # exponent is "locked in" cube = partial(power, exponent=3) print(square(5)) # 25 (power(5, exponent=2)) print(cube(5)) # 125 (power(5, exponent=3)) # Practical use: adapting a two-argument function for map(), which only supplies one nums = [1, 2, 3, 4] print(list(map(square, nums))) # [1, 4, 9, 16]
💡 partial and closures (Q72) solve overlapping problems — if asked "how else could you achieve this," showing you could write an equivalent closure-based factory function (like make_multiplier in Q66) demonstrates you understand why partial exists as a convenient shortcut, not as the only way.
Recommended resourcesAffiliate links · may earn us a commission