ProgrammingPython Developer

Tell us about lambda functions in Python. What are their limitations compared to regular functions? In what situations are they preferable to use, and in what situations are they undesirable?

Pass interviews with Hintsage AI assistant

Answer

Lambda function is an anonymous function defined using the lambda keyword. It is typically used where a short function is needed "once and in place."

add = lambda x, y: x + y print(add(1, 2)) # 3

Limitations of lambda functions:

  • A lambda can only contain a single expression — which is also the return value; you cannot perform multi-line computations, use return, or if-else conditions (only in the form of a ternary expression).
  • You cannot use complex code with try/except, loops, etc.
  • A lambda does not have full documentation capabilities (you cannot add a docstring).
  • Lambda functions are harder to read, especially when nested.

When lambda is useful:

  • In single-line sorting/filtering keys (key arguments; e.g., in sorted, filter, map).
  • When code reuse is not required — local operations, quickly "insert a function."

When to avoid lambda:

  • In complex logic: for reuse, with large amounts of code or conditions, for clarity and readability it is better to extract to a named def function with a docstring.

Trick Question

Question: Can lambda functions capture variables from the outer scope, and how does this affect their behavior when used within loops?

Answer: Lambda functions can capture variables from the outer context (lexical closure). When defined inside a loop, this often leads to unexpected behavior — the lambda uses the current value of the variable at the time of the call, not what it "was at the time of definition."

funcs = [] for i in range(3): funcs.append(lambda: i) # all functions will return 2 (i=2 after the loop) print([f() for f in funcs]) # [2, 2, 2]

To capture the "old" value:

funcs = [] for i in range(3): funcs.append(lambda i=i: i) print([f() for f in funcs]) # [0, 1, 2]

Examples of real mistakes due to lack of awareness of the nuances of the topic


Story

In the project, a lambda was used to filter a list of dictionaries by a specific key. The lambda inside the loop captured a variable that had a different (unexpected) value at the time of the call. The result was incorrect filtering and errors in reporting.


Story

A large project on Django: complex validation form implemented as a long expression within a lambda function. Subsequently, the business logic changed, and the lambda could no longer accommodate all the code, necessitating a rewrite to a regular function. The lambda slowed down debugging.


Story

In one startup, lambda was unsuccessfully applied for passing a sorting function, forgetting that it returns an incorrect type (for example, a list instead of a tuple). This led to unpredictable sorting and bugs with data deduplication.