Skip to the solution
MediumDSA6 min read

What are lambda functions and map/filter/reduce?

823 views

The problem

Question presented to candidate: "What is a lambda in Python and what are its limits? Then show me map, filter and reduce on a list of numbers β€” and tell me when you would use a list comprehension instead."

What a strong answer should cover:

  • A lambda is an expression that creates an ordinary function object with one expression as its body (no statements, no annotations); its __name__ is <lambda> and it compiles to the same bytecode as the equivalent def
  • Best use: a short throwaway callback, especially key= for sorted, min, max; PEP 8 says to use def instead of assigning a lambda to a name
  • In Python 3, map and filter return lazy, single-use iterators, not lists; map with several iterables stops at the shortest; filter(None, xs) keeps truthy items
  • reduce lives in functools since Python 3.0 and folds left to right, f(f(f(a, b), c), d); without an initializer an empty input raises TypeError
  • Trade-offs: comprehensions and built-ins (sum, max, any, math.prod) are usually clearer; the operator module avoids trivial lambdas; lambdas in loops capture variables late

Code / implementation expected: Yes β€” a sort with a lambda key, a map/filter/reduce pipeline, and the comprehension equivalent.

  • lambda
  • functional

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read Β· 8 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonLambdas: what they are, what they cannot do, and late binding
Pythonmap, filter and reduce: laziness, edge cases and the comprehension equivalents

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 65 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

What is the difference between classmethod and staticmethod?

Continue