Python Lambda, Map, Filter and Reduce Interview Questions
Last updated 2026-11-19
Functional features in Python are asked about because they test your comfort with first-class functions. Interviewers expect you to read and write lambdas, to know map, filter and reduce, to prefer comprehensions where that is more idiomatic, and to spot the closure pitfalls that surround them.
This page works through the questions in order of difficulty, with the Python 3 behaviours that older tutorials get wrong, such as map and filter returning lazy iterators and reduce living in functools.
| Level | Fresher to 3 years |
|---|---|
| Focus | lambda, higher-order functions, functools, operator |
| Version | Python 3.9 and later |
A balanced stance
A strong answer shows you know both the functional tools and when not to use them. Comprehensions are usually clearer than map and filter with a lambda, but map with a named function or key= with a lambda are perfectly idiomatic.
- A lambda is limited to a single expression and cannot contain statements
- PEP 8 discourages assigning a lambda to a name; use def instead
- map and filter return iterators in Python 3, so wrap them in list to see values
Related topics
Late binding in lambdas is covered with a worked trap on the main Python page, and decorators build directly on these ideas in decorators interview questions. See also how to crack a Python interview.
Python Lambda, Map, Filter and Reduce Interview Questions: questions with worked answers
1 What is a lambda function in Python?
easyA lambda is an anonymous function defined with the lambda keyword and a single expression whose value is returned automatically. It can take any number of arguments, including defaults and *args, but no statements such as assignment, return or loops. It is most useful as a small argument to functions like sorted, min, max and map.
pythonsquare = lambda x: x * x print(square(5)) # 25 print((lambda a, b=2: a + b)(3)) # 52 How do map and filter work in Python 3?
easymap(fn, *iterables) applies the function to each item and filter(fn, iterable) keeps items for which the function is truthy. Both return lazy iterators, not lists, so they can be consumed only once. With filter, passing None keeps truthy items. map with several iterables stops at the shortest.
pythonnums = [1, 2, 3, 4] m = map(lambda x: x * 2, nums) print(m) # <map object at 0x...> print(list(m), list(m)) # [2, 4, 6, 8] [] print(list(filter(None, [0, 1, "", "a"]))) # [1, 'a'] print(list(map(pow, [2, 3], [3, 2]))) # [8, 9]3 What does reduce do, and where do you import it from?
mediumfunctools.reduce(fn, iterable, initial) folds a sequence into one value by applying the function cumulatively: fn(fn(a, b), c) and so on. It was a built-in in Python 2 and moved to functools in Python 3. Provide an initial value so empty input does not raise TypeError. For sums and products, sum() and math.prod are clearer.
pythonfrom functools import reduce print(reduce(lambda a, b: a * b, [1, 2, 3, 4])) # 24 print(reduce(lambda a, b: a + b, [], 0)) # 0 print(reduce(max, [3, 9, 2])) # 94 Compare list comprehension with map and filter.
mediumThey express the same thing. A comprehension such as [x * 2 for x in nums if x > 1] combines mapping and filtering in one readable line, is usually faster than map with a lambda, and works everywhere. map is neat when you already have a named function, for example map(int, parts), and it stays lazy. Choose the form that reads best, and use a generator expression when you do not need a list.
5 How do you use lambda with sorted, min and max?
mediumThe key argument takes a one-argument function that returns the sort key. Lambdas are the usual way to sort records by a field or by a computed value. min and max accept the same key. A tuple key sorts by several fields, and negating a numeric field gives mixed ascending and descending order.
pythonpeople = [("Ravi", 25), ("Asha", 30), ("Neha", 25)] print(sorted(people, key=lambda p: (p[1], p[0]))) # [("Neha", 25), ("Ravi", 25), ("Asha", 30)] print(max(people, key=lambda p: p[1])) # ('Asha', 30)6 Predict the output: lambdas in a loop and default arguments.
hardAll lambdas created in the loop close over the same variable, so they see its final value. A default argument is evaluated when the lambda is defined, capturing the current value. functools.partial gives the same fix without the hidden parameter.
pythonfuncs = [lambda x: x + i for i in range(3)] print([f(10) for f in funcs]) # [12, 12, 12] funcs = [lambda x, i=i: x + i for i in range(3)] print([f(10) for f in funcs]) # [10, 11, 12]7 What is functools.partial?
mediumpartial(fn, *args, **kwargs) returns a new callable with some arguments fixed in advance. It is useful to adapt a function to an API that expects fewer arguments, for example a callback, without writing a lambda. The result keeps the original function in .func and the fixed arguments in .args.
pythonfrom functools import partial int_base2 = partial(int, base=2) print(int_base2("1010")) # 10 power_of_two = partial(pow, 2) print(power_of_two(5)) # 328 What is a higher-order function, and what is a pure function?
mediumA higher-order function takes functions as arguments or returns one, like sorted with key, map and decorators. A pure function always returns the same output for the same input and has no side effects such as modifying globals or doing I/O. Pure functions are easier to test, cache and run in parallel, which is why lru_cache is only safe on them.
9 Write a function that composes two functions.
mediumReturn a new function that applies the second function first and passes the result to the first. This shows closures and higher-order functions together. For many functions, reduce can fold a list of functions into one.
pythonfrom functools import reduce def compose(*fns): return lambda x: reduce(lambda acc, f: f(acc), reversed(fns), x) inc = lambda x: x + 1 dbl = lambda x: x * 2 print(compose(inc, dbl)(5)) # 11 : dbl first, then inc10 What do any and all return for empty inputs?
mediumany(iterable) is True if at least one item is truthy, so any of an empty iterable is False. all(iterable) is True if every item is truthy, so all of an empty iterable is True, vacuously. Both short-circuit as soon as the answer is known, and work well with generator expressions to avoid building a list.
pythonprint(any([]), all([])) # False True print(all(x > 0 for x in [1, 2, 3])) # True print(any(c.isdigit() for c in "abc1")) # True11 Predict the output: filter with a lambda that has side effects, evaluated lazily.
hardBecause filter is lazy, the function is not called until the result is consumed, and each item is tested only once during iteration. If you print inside the lambda and never iterate, nothing prints. Consuming it twice does not call the function again for the second pass because the iterator is exhausted.
pythonf = filter(lambda x: print("check", x) or x > 1, [1, 2, 3]) print("created") # created (nothing checked yet) print(list(f)) # check 1 / check 2 / check 3 / [2, 3]12 What are the operator module functions for, and why use itemgetter?
mediumoperator exposes the built-in operators as functions: add, mul, itemgetter, attrgetter. itemgetter and attrgetter are faster and clearer than equivalent lambdas for sort keys and map calls, and itemgetter can fetch several keys at once as a tuple.
pythonfrom operator import itemgetter, attrgetter rows = [{"n": "b", "s": 2}, {"n": "a", "s": 2}, {"n": "c", "s": 1}] print([r["n"] for r in sorted(rows, key=itemgetter("s", "n"))]) # ['c', 'a', 'b']13 What is the difference between a closure and a lambda?
mediumThey are independent ideas. A lambda is only syntax for an anonymous function. A closure is any function, named or not, that remembers variables from its enclosing scope after that scope has finished. A lambda created inside another function is a closure if it uses the outer variables, and a def can be a closure too.
Frequently asked questions
Is lambda faster than def?
No. A lambda compiles to the same kind of function object, so there is no speed difference. Its advantage is brevity at the point of use.
Why does map return an object instead of a list?
In Python 3 it is lazy to save memory. Wrap it in list or loop over it to get values.
Can a lambda contain an if statement?
It can contain a conditional expression, such as lambda x: 'even' if x % 2 == 0 else 'odd', but not an if statement block.
Should I use reduce in modern Python?
Rarely. Prefer sum, max, min, any, all or a loop when they are clearer. Reduce is fine for genuinely cumulative operations that have no built-in.
Related guides
More in Programming Language Interview Questions by Language
- Python List, Dict and Set Interview Questions
- Python Memory Management Interview Questions
- Python Multithreading and Multiprocessing Interview Questions
- Python OOPs Interview Questions
- Python String Interview Questions
- SQL CTE and Recursive Query Interview Questions
- SQL GROUP BY and HAVING Interview Questions
- SQL Indexes Interview Questions
- SQL Interview Questions and Answers
- SQL Interview Questions for Freshers
- SQL Joins Interview Questions
- SQL Query Practice: Interview Questions with Solutions