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:
When lambda is useful:
sorted, filter, map).When to avoid lambda:
def function with a docstring.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]
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.