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 equivalentdef - Best use: a short throwaway callback, especially
key=forsorted,min,max; PEP 8 says to usedefinstead of assigning a lambda to a name - In Python 3,
mapandfilterreturn lazy, single-use iterators, not lists;mapwith several iterables stops at the shortest;filter(None, xs)keeps truthy items reducelives infunctoolssince Python 3.0 and folds left to right,f(f(f(a, b), c), d); without an initializer an empty input raisesTypeError- Trade-offs: comprehensions and built-ins (
sum,max,any,math.prod) are usually clearer; theoperatormodule 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.