1. Analyze the Request:
* Topic: Lambda function (anonymous function).
* Requirement: Definition + Example in Python.
-
Define "Lambda Function" (Anonymous Function):
- What is it? A function without a name.
- Why use it? For short, simple operations used once (or a few times). It avoids cluttering the code with a formal
def block if the logic is trivial.
- Syntax (General): Usually takes arguments, contains a single expression, and returns the result of that expression.
- Origin: Lambda calculus (Alonzo Church).
-
Define "Lambda Function" (Python specific):
- Keyword:
lambda.
- Syntax:
lambda arguments: expression.
- Key restriction: Can only contain one expression (no statements like
if x: ... else: ... inside a block, though conditional expressions x if y else z are allowed). Returns implicitly.
-
Drafting the Explanation:
- Start with a clear, concise definition. It's a small anonymous function.
- Mention the key characteristic: defined in one line.
- Mention the use case: higher-order functions (map, filter, reduce) or as a quick callback.
-
Creating Examples (Python):
- Basic Example: Simple addition or squaring.
- Practical Example (The "Why"): Just showing
add isn't super convincing because def add is better. The real power is inside things like sorted() or filter().
- Scenario: Sorting a list of tuples by the second item.
- Data:
[('Apple', 3), ('Banana', 1), ('Cherry', 2)].
- Code:
sorted(data, key=lambda x: x[1]).
-
Refining the Structure:
- Definition: What is it?
- Syntax: How to write it?
- Basic Example: Compare
def vs lambda.
- Practical Example: Show where it actually shines (e.g.,
sorted).
- Pros/Cons (Optional but helpful): Readability vs. Convenience.
-
Writing the Content (Iterative refinement):
-
Final Polish: Ensure the tone is helpful and the code is correct. (Self-correction: Make sure to emphasize that it returns the value automatically without the return keyword).
-
Final Output Generation: (This matches the provided good response).
- Heading: Definition.
- Python Syntax.
- Example 1: Basic math.
- Example 2: Inside
filter or sorted (to show utility).
Let's go with the sorted example as it's the most common interview/production use case.
-
Constructing the Final Response: (See actual output).
A lambda function (also known as an anonymous function) is a small, unnamed function defined in a single line of code.
Unlike a standard function defined with the def keyword, a lambda function is restricted to a single expression. It is often used for short, simple operations where defining a full function would be unnecessarily verbose.
Syntax
In Python, the syntax is:
lambda arguments: expression
lambda: The keyword used to define the function.
arguments: A comma-separated list of parameters (inputs).
expression: The code that is evaluated and returned automatically.
Examples
1. Basic Example (Math)
Here is a comparison between a standard function and a lambda function that does the same thing (doubles a number).
Standard Function:
def double(x):
return x * 2
print(double(5)) # Output: 10
Lambda Function:
double = lambda x: x * 2
print(double(5)) # Output: 10
2. Practical Example (Using with sort)
Lambda functions are most commonly used as arguments to higher-order functions (functions that take other functions as arguments).
For example, if you want to sort a list of tuples based on the second item in each tuple:
points = [(1, 5), (3, 2), (8, 10), (4, 1)]
# We use the lambda to tell sort() to look at index 1 (the second number)
points.sort(key=lambda x: x[1])
print(points)
Output:
[(4, 1), (3, 2), (1, 5), (8, 10)]
3. Practical Example (Using with filter)
You can use lambda to quickly filter a list. Here, we filter a list to keep only the even numbers.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# filter(function, iterable) returns items where the function returns True
even_numbers = list(filter(lambda x: (x % 2 == 0), numbers))
print(even_numbers)
Output:
[2, 4, 6, 8, 10]
Summary
- Anonymous: It doesn't strictly require a name (though you can assign one, as seen in Example 1).
- Single Expression: It cannot contain statements (like
if, for, or while blocks) inside the function body, though conditional expressions (x if y else z) are allowed.
- Concise: Best used for simple, throwaway operations.