A lambda function in Python is a small anonymous function, which can take any number of arguments but can only have one expression.
The syntax for a lambda function is:
lambda arguments: expression
It is also known as anonymous function because it doesn’t have any name and it is defined using the keyword “lambda“. It can be used wherever function objects are required. They are often used in functional programming, such as in the map(), filter(), and reduce() functions.
Here’s an example of a lambda function that takes two arguments (x, y) and returns their sum:
add = lambda x, y: x + y print(add(3, 4)) # Output: 7
You can also use a lambda function as an argument to another function.
Here’s an example where a lambda function is used to sort a list of numbers in descending order:
numbers = [3, 1, 4, 2, 5] sorted_numbers = sorted(numbers, key=lambda x: -x) print(sorted_numbers) # Output: [5, 4, 3, 2, 1]
In this example, the sorted() function takes a key argument, which is a function that is used to extract a comparison key from each list element. The lambda function lambda x: -x takes a number x and returns its negation, so when passed to the sorted() function, it sorts the list in descending order.
Here are a few examples of how lambda functions can be used in functional programming in Python:
map() function: The map() function applies a given function to all items in an input list, and returns a new list with the results.
Here’s an example where a lambda function is used to square all the numbers in a list:
numbers = [1, 2, 3, 4, 5] squared_numbers = list(map(lambda x: x*x, numbers)) print(squared_numbers) # Output: [1, 4, 9, 16, 25]
filter() function: The filter() function filters the items in an input list based on a given function, and returns a new list with the items that pass the test.
Here’s an example where a lambda function is used to filter all the even numbers from a list:
numbers = [1, 2, 3, 4, 5] even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) print(even_numbers) # Output: [2, 4]
reduce() function: The reduce() function applies a given function to the items in an input list, in a cumulative manner and returns a single result.
Here’s an example where a lambda function is used to find the product of all numbers in a list:
from functools import reduce numbers = [1, 2, 3, 4, 5] product = reduce(lambda x, y: x*y, numbers) print(product) # Output: 120
These are just a few examples of how lambda functions can be used in functional programming in Python. In addition to these, they can also be used in combination with other functional programming constructs such as list comprehension, map, filter etc.