✏️ Explanatory Question

What is the purpose of the lambda keyword in Python?

👁 258 Views
📘 Detailed Answer
💡

Answer with Explanation

The lambda keyword in Python is used to create anonymous functions, also known as lambda functions. Anonymous functions are small, one-time use functions that do not have a name. They are often used when a function is required only once in a specific context and it is not necessary to give it a name.

The syntax of a lambda function is as follows:


lambda arguments: expression

where:

  • arguments are the input parameters to the lambda function.
  • expression is a single expression that is evaluated and returned when the lambda function is called.

Lambda functions can be assigned to a variable or passed as an argument to another function, just like regular functions.

For example:


add = lambda x, y: x + y
print(add(3, 4)) # Output: 7