Lambda
Try to understand the difference between a normal def defined function and lambda function. This is a program that returns the cube of a given value:
# Python code to illustrate cube of a number
# showing difference between def() and lambda().
def cube(y):
return y*y*y
lambda_cube = lambda y: y*y*y
# using the normally
# defined function
print(cube(5))
# using the lamda function
print(lambda_cube(5))
output:
125
125
Without using Lambda:
- Here, both of them return the cube of a given number. But, while using def, we needed to define a function with a name cube and needed to pass a value to it. After execution, we also needed to return the result from where the function was called using the return keyword.
Using Lambda:
- Lambda definition does not include a “return” statement, it always contains an expression that is returned. We can also put a lambda definition anywhere a function is expected, and we don’t have to assign it to a variable at all. This is the simplicity of lambda functions.
Lambda functions can be used along with built-in functions like filter()
, map()
and reduce()
.
lambda() with filter()
The filter()
function in Python takes in a function and a list as arguments. This offers an elegant way to filter out all the elements of a sequence “sequence”, for which the function returns True
.
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(filter(lambda x: (x%2 == 0) , my_list))
print(new_list)
ages = [13, 90, 17, 59, 21, 60, 5]
adults = list(filter(lambda age: age>18, ages))
print(adults) # above 18 yrs
output:
[4, 6, 8, 12]
[90, 59, 21, 60]
lambda() with map()
The map()
function in Python takes in a function and a list as an argument. The function is called with a lambda function and a list and a new list is returned which contains all the lambda modified items returned by that function for each item.
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(map(lambda x: x * 2 , my_list))
print(new_list)
cities = ['novi sad', 'ljubljana', 'london', 'new york', 'paris']
# change all city names
# to upper case and return the same
uppered_cities = list(map(lambda city: str.upper(city), cities))
print(uppered_cities)
output:
[2, 10, 8, 12, 16, 22, 6, 24]
['NOVI SAD', 'LJUBLJANA', 'LONDON', 'NEW YORK', 'PARIS']
reduce
reduce()
works differently than map()
and filter()
. It does not return a new list based on the function
and iterable we've passed. Instead, it returns a single value.
Also, in Python 3 reduce()
isn't a built-in function anymore, and it can be found in the functools
module.
The syntax is:
reduce(function, sequence[, initial])
reduce()
works by calling the function
we passed for the first two items in the sequence. The result returned by the function
is used in another call to function
alongside with the next (third in this case), element.
The optional argument initial
is used, when present, at the beginning of this "loop" with the first element in the first call to function
. In a way, the initial
element is the 0th element, before the first one, when provided.
lambda() with reduce()
The reduce() function in Python takes in a function and a list as an argument. The function is called with a lambda function and an iterable and a new reduced result is returned. This performs a repetitive operation over the pairs of the iterable.
from functools import reduce
my_list = [1, 1, 2, 3, 5, 8, 13, 21, 34]
sum = reduce((lambda x, y: x + y), my_list)
print(sum) # sum of a list
print("With an initial value: " + str(reduce(lambda x, y: x + y, my_list, 100)))
88
With an initial value: 188
These functions are convenience functions. They are there so you can avoid writing more cumbersome code, but avoid using both them and lambda expressions too much, because "you can", as it can often lead to illegible code that's hard to maintain. Use them only when it's absolutely clear what's going on as soon as you look at the function or lambda expression.