lambda: Anonymous, single-line statement for quick tasks.
Python Lambda Functions
Python lambda expression are small, anonymous utility created using the lambdareserved keyword of Python. These statements are typically one-liners designed for simple operations, often used as arguments in higher-order functions like map(), filter(), or sorted(). Lambda functions are also known as “inline operation” because they’re usually written where they’re used, without formally defining a function with def.
Syntax
The basic syntax of a lambda Expression:
lambdaarguments: expression
- arguments: The inputs to the lambda Expression, which can be one or more parameters separated by commas.
- expression: A single expression that the lambda statement returns.
Tip: For reusable and complex logic, use a function; for short, one-time operations, use a lambda.
Example 1: Basic Lambda Expression
Here’s a simple example of a lambda statement that adds two numbers.
add = lambdax, y: x+yprint(add(3, 5))
Output:
8
Example 2: Lambda statement with map()
Lambda statements are often used with map() to apply an operation to each item in an iterable, such as a list.
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery,
and web development at plus2net. The tutorials focus on clear explanations, working
examples, and code that readers can test and adapt while learning.