Lambda Function

Lambda and anonymous function expressions in Python.

Python - Lambda function:

A lambda function in Python is a small, anonymous function that can have any number of arguments, but can only have one expression. Lambda functions are often used when you need a simple function for a short period of time and don't want to define a full function using the 'def' keyword.

lambda arguments: expression

Here's a simple example of a lambda function that adds two numbers:

py Copy Code
add = lambda x, y: x + y

result = add(3, 5)
print(result)
Output:
8

Lambda functions are often used in conjunction with higher-order functions like 'map()', 'filter()', and 'reduce()', or as arguments to functions that expect a function as an argument.

For example, using a lambda function with 'map()':

py Copy Code
numbers = [1, 2, 3, 4, 5]
squared = map(lambda x: x ** 2, numbers)
print(list(squared))
Output:
[1, 4, 9, 16, 25]

And with 'filter()':

py Copy Code
numbers = [1, 2, 3, 4, 5]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers))
Output:
[2, 4]

Lambda functions can make code more concise and readable in certain situations, particularly when used in combination with these higher-order functions. However, they should be used judiciously, as using them excessively can lead to less readable code.

Lambda functions and anonymous functions the same?

Lambda functions and anonymous functions are often used interchangeably, but they are not exactly the same.

An anonymous function is a function that does not have a name. In programming languages, you can define functions without naming them. These functions are usually defined inline where they are needed and can be assigned to variables or passed as arguments to other functions. Anonymous functions are commonly used in functional programming paradigms and in languages that support first-class functions, such as JavaScript, Python, and others.

A lambda function is a specific kind of anonymous function. It is a small, anonymous function that is defined using the lambda keyword. Lambda functions are often used in languages like Python to create simple, one-line functions without needing to explicitly define a function using the def keyword. Lambda functions are limited in functionality compared to regular functions, as they are restricted to a single expression.

In summary, while all lambda functions are anonymous functions, not all anonymous functions are lambda functions. Lambda functions are a subset of anonymous functions that have a specific syntax and usage pattern, particularly common in languages like Python.

What's Next?

We actively create content for our YouTube channel and consistently upload or share knowledge on the web platform.