Lambda

A Python lambda function is a small, anonymous function that can take any number of arguments but can only have one expression. Lambda functions are used when a regular function is not required or when a small function is needed to be defined inline in another code block.

Python

# Define a lambda function that takes one argument and returns its square
square = lambda x: x ** 2

# Call the lambda function with an argument of 5
result = square(5)

# Print the result
print(result)


#output : 25

Python

# Define a lambda function to add two numbers
add = lambda x, y: x + y

# Call the lambda function with arguments and print the output
result = add(2, 3)
print(result)


#output : 5

Using lambda functions as parameters can be particularly useful when working with functions that take other functions as arguments, such as the built-in map() and filter() functions. These functions apply a given function to a sequence of values and return a new sequence with the results.

map() function

Python

numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared)

#output : [1, 4, 9, 16, 25]

filter() function

Python

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)

#output : [2, 4, 6, 8, 10]

Lambda functions can also be used with other functions that take functions as parameters, such as sorted() and reduce(). By using lambda functions as parameters, we can write more concise and expressive code that is easier to read and understand.

sorted() function

Python

data = [(1, 5), (3, 2), (4, 9), (2, 8), (5, 1)]
sorted_data = sorted(data, key=lambda x: x[1])
print(sorted_data)

#output : [(5, 1), (3, 2), (1, 5), (2, 8), (4, 9)]

reduce() function

Python

from functools import reduce

numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
print(product)

#output : 120
Next