Skip to main content

Lambda Function

Lamba Function

A lambda function is a small and anonymous function.

"Anonymous function is a function without a name".

We can define this function using lambda keyword.

Syntax: lambda argument : expression

Example 1:

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

result = lambda a, b : a + b

print(result(5, 6)) Output: 11

Example 2:

Here's another example which calculated based on operator sequence.

exp  = lambda x, y, z : (x + y) * z

print(exp(2,1,3))

Output: 9

"A lambda fun can take any number of args but can only have one expression".

Lambda functions are particularly useful in situations where you need a quick, one-off function without defining a formal function using `"def".

Advanced level examples:

1. Using map() function:

numbers = [1, 2, 3, 4, 5]

squared = list(map(lambda x: x**2, numbers))
   
print(squared)  

Output: [1, 4, 9, 16, 25]

2. Using filter() function:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

even_numbers = list(filter(lambda x: x % 2 == 0, numbers))

print(even_numbers) 

Output: [2, 4, 6, 8, 10]

3. Using reduce() function:

numbers = [1, 2, 3, 4, 5]

sum = reduce(lambda x, y: x + y, numbers)   

print(sum)  

Output: 15

Comments