w3resource

What is a lambda function in Python, and how is it defined?

Python Lambda Functions: Definition and Usage

Python lambda functions are small, anonymous, and single-line functions that can be defined without a name. It is also known as an "inline function" or "lambda expression." Unlike regular functions created with the "def" keyword, lambda functions are created with the "lambda" keyword. Lambda functions are often used for short, one-time tasks, especially in cases where defining a full-fledged function using "def" would be unnecessary or cumbersome.

The syntax for defining a lambda function is as follows:

lambda arguments: expression

In the above syntax:

  • lambda: A lambda function is defined by this keyword.
  • arguments: Separated by commas, these represent the arguments to the lambda function. It can have zero or more arguments.
  • expression: It is a single expression that gets evaluated and returned as the result of the lambda function.

Here's an example of a simple lambda function that takes two arguments and returns their product:

result = lambda x, y: x + y

In the above example, lambda x, y: x * y creates a lambda function that takes two arguments x and y and returns their product. Note that lambda functions can have multiple arguments separated by commas.

In higher-order functions like map, filter, and sorted, lambda functions are often used when a short, throwaway function is needed, or when passing a simple function as an argument.



Follow us on Facebook and Twitter for latest update.