Lambda functions are some of the most underrated yet extremely easy to use functions in all of Python. They are hard to grasp for a beginner, however, quickly become an indispensable tool in your kit when you get the hang of it.
The function is named so, because it becomes easy to declare an anonymous function under the guise of the keyword lambda. It is essentially a function that has no name. They have all the functionalities of a regular function.
Declaring a Lambda Function
The key to understanding lambda functions is to first look at how the syntax works. Any number of arguments can be included in the argument(s) part of the code, but only one expression is produced.
lambda argument(s): expression
The lambda function result can only be outputted through one variable that is assigned.
An example of the function in use:
sum = lambda x: x + 2
print(sum(5))
Output:
7
The lambda function here is sum = lambda x: x+2
, the x
is the argument and x + 2
is the expression that is to be evaluated.
The sum
here is the identifier to which the function object is assigned. Hence, it still remains nameless as mentioned earlier.
The filter()
function
The filter()
built-in function has two arguments:
filter(object, iterable)
The object
here is the lambda function that runs on the iterable
. The iterable
in question can be sets, tuples, lists or any other grouping of elements. The filter()
function returns every iterable
element that returns True
on running the lambda function on it.
An example program to return elements greater than 2 is as follows:
num_list = [2, 4, 6]
filtered_list = list(filter(lambda num: (num>2), num_list)
print(filtered_list)
Output:
[4, 6]
The map()
function
The map()
function is another built-in function that takes a function object
and iterable
.
map(object, iterable)
The object
here is the lambda function and the iterable
is the grouping of elements (lists, tuples, dictionaries or sets) on which the action is executed. The object
is mapped onto every element in the iterable
, according to the lambda function.
Example program that adds 2 to every element in the iterable:
num_list = [2, 4, 6]
filtered_list = list(filter(lambda num: (num+2), num_list)
print(filtered_list)
Returns the output:
[4, 6, 8]
Conclusion
Lambda functions are commonly used when you need to pass a function as an argument into a bigger function. Knowledge of these functions shortens your code and makes it clean. Make sure to use them in your next project!