Lambda or Anonymous Functions in Python
A lambda function in Python is a small, anonymous function defined with the lambda
keyword. Unlike regular functions defined using def
, lambda functions can have any number of arguments but can only have one expression. They are often used for short, throwaway functions and can be defined in a single line.
Key Points on Lambda Functions:
- Lambda functions are syntactically restricted to a single expression.
- They can take any number of arguments but only one expression, which is evaluated and returned.
- Lambda functions are often used in conjunction with functions like
map
,filter
, andreduce
. - They are useful for writing quick functions without formally defining them using
def
. - Lambda functions can be assigned to variables, making them reusable.
Syntax of Lambda Function:
Syntax Example
lambda arguments: expression
Example of Lambda Function in Python:
This example demonstrates a basic lambda function that squares a number.
Code Example 1
square = lambda x: x ** 2
result = square(5)
print(result)
Output
Using Lambda with Functions:
This example shows how to use a lambda function with the map
function to double each number in a list.
Code Example 2
numbers = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, numbers))
print(doubled)
Output
Using Lambda with Filter:
This example demonstrates using a lambda function with the filter
function to get even numbers from a list.
Code Example 3
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
Output
Advantages of Using Lambda Functions:
- Conciseness: Lambda functions allow for compact function definitions.
- Anonymous: They can be defined and used without naming, which can simplify code for temporary functions.
- Higher-Order Functions: They are frequently used with functions like
map
,filter
, andreduce
for functional programming styles.
Lambda functions provide a flexible way to define small functions without the overhead of a full function definition, making them particularly useful in functional programming paradigms.