lambda() function
lambda is an anonymous function - function without a name.
The lambda function can have any number of arguments but only one expression.
Watch the example:
#lambda
x = lambda a, b: a + b
print(x(5, 10))
In the example above the function get 2 arguments - a, b.
It returns the sum of the arguments.
When to Use Lambdas?
Lambda - map, reduce, filter
The example above shows well how the lambda operates. However it doesn't show a classic use of the lambda.
We mostly use the lambda functions when we don't have to call the function again.
Like the use of map(),
reduce() and filter().
Watch the example:
#lambda
my_list = [1, 2, 3, 4, 5]
my_map_doubled = map(lambda a: a * 2, my_list)
my_list_doubled = list(my_map_doubled)
print(my_list_doubled)
Lambda - nested functions
Another appropriate example is the use of small nested functions:
#lambda
def my_power(x):
return lambda a: a ** x
#create a function that returns the power of 3
power_3 = my_power(3)
print(power_3(2))
print(power_3(3))
Exercise
- Create a list of arbitrary numbers.
- Use the map() function to apply a lambda function on the list.
- Print out the list.
#Write here your code: