Objective: In this brief post, you're going to learn what anonymous functions are, and when to use them
Anonymous functions in python?
So what is a lambda function?
Lambda functions are functions in python without names. These functions are small and they can collect multiple arguments but can only have one expression.
function = lambda parameter : expression
From the above syntax, you can see that the lambda function is created using the lambda keyword and afterward, the parameters of the function can be written, then whatever expression you want for your function can be written after the colon.
function = lambda firstNumber, secondNumber : firstNumber + secondNumber print(function(1, 2))
When to use the anonymous function in python:
Since lambda functions can only have one expression, it makes sense to use them when you want to carry out a really small task. Lambda functions are also best used in other functions like map(), reduce() and filter() where they can be passed as arguments.
Example with the filter() function:
numbers = [1,3,3,4,5,6,4,3,6,7] morethanfive = list(filter(lambda x : x > 5, numbers)) print(morethanfive)
[6, 6, 7]