A lambda function is a small anonymous function that returns an object. This function is assigned to a variable o it is part of a function bigger.
Just as in a normal function the def keyword is needed, for lambda functions we need the lambda keyword.
The function lambda is more legible when we have to do small things.
The structure of the lambda functions is:
lambda args: expression
- lambda: keyword to express that a function is a lambda function
- args: are arguments separated for commas
- expression: is an expression that returns an object
Here some examples for we obtain a better understanding of lambda functions.
sum = lambda x, y: x + y
total = sum(3, 5) // 8
difference = lambda x, y: x -y
value = difference(8, 5) // 3
primes = [1, 2, 3, 5, 7]
primes_squared = map(lambda n: n*n, primes) // 1, 4, 9, 25, 49
numbers = [1, 2, 3, 5, 8]
odd = filter(lambda n: n%2 == 1, numbers) // [1, 3, 5]
It is my first post in Dev.to, I hope that it will be helpful for you.