lambda
A lambda is a small unnamed function written as a single expression.
Used in 63 lessons of the course, from Project 00.
A lambda creates a function in one line. Read it as lambda parameters: expression. What comes after the colon is what the function returns, with no return needed.
It is equivalent to a def, but unnamed and limited to one expression: no multiple lines, no assignment statements.
You use it to pass a small function as an argument without defining it separately. In the course it shows up in dicts of checks like "factual": lambda answer: bool(re.search(...)): each value is a function that takes the answer and returns True or False. That keeps the rule next to its name, and you call it later.
double = lambda x: x * 2
print(double(4))
Reach for it when: you need a short, one-off function, for example as a `key=` or as a value in a dict. If it needs several lines or is reused a lot, write a `def`.
Examples
Common mistake
f = lambda x: return x * 2 print(f(2))
Why: A lambda only accepts an expression, and `return` is a statement. The value is already returned for you.
How to write it: Drop return: lambda x: x * 2.
Common mistake
checks = [lambda: i for i in range(3)] print([f() for f in checks])
Why: The lambda looks up `i` when it is called, not when it is created, and by then `i` is 2.
How to write it: Freeze the value with a default parameter: lambda i=i: i.
