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.
Structure
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
Examples
Here some examples for we obtain a better understanding of lambda functions.
Sum
sum = lambda x, y: x + y
total = sum(3, 5) // 8
Difference
difference = lambda x, y: x -y
value = difference(8, 5) // 3
Map
primes = [1, 2, 3, 5, 7]
primes_squared = map(lambda n: n*n, primes) // 1, 4, 9, 25, 49
Filter
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.
Top comments (0)