Lambda expression is useful for creating small, one time use functions though the functions can also be given a name.
It can have multiple arguments but just a single expression as the function body.
The basic syntax to create a lambda function is
lambda arguments: function body
For example
lambda x: x**2
This function takes in x and returns x2. Here, lambda is the keyword, x is the argument and the expression after the colon is the function body.
These functions can also be given a name,
sqr = lambda x: x**2
sqr(5) #output : 25
Multiple arguments can also be provided
lambda x,y: x * y
or
lambda x,y,z: x*y*z
These functions when given a name are equivalent to the functions defined by using the
def
keyword.For example
def solve_quad(a,b,c):
d = b**2 - (4*a*c)
x1 = (-b + math.sqrt(d))/2*a
x2 = (-b - math.sqrt(d))/2*a
return (x1,x2)
This function takes in coefficients a, b, c of a quadratic equation and returns its roots as a tuple. It could be converted to a lambda function in the following way,
solve_quad = lambda a,b,c: ((-b + math.sqrt(b**2 - 4*a*c))/(2*a),(-b - math.sqrt(b**2 - 4*a*c))/(2*a) )
This function converted into a lambda expression is perhaps not the most motivating example but it nonetheless displays how to do it. This examples also shows that some functions are better written with a traditional
def
keyword rather than as a lambda expression as with def
it can be spaced out on multiple lines which increases readability.Using lambda with map()
Map is a higher order function and in commonly used in functional programming.It is used to apply a same function to an iterable like list.
l = [x for x in range(100)]
t = list(map(lambda x, x**2, l)) #output: [0,1,4,9,16,25....,10000]
This simple application of map function takes in a list and returns and new list that consists the squares of all the elements in the argument that has been passed to it. So basically map can be used to replace loops where the body of the loop is just some function or multiple functions applied onto the element of the iterable. Another example would be,
l = ["MaN", "Sun", "bUN"]
result = list(map(lambda x: x.lower(), l))
#output: ["man", "sun", "bun"]
This function takes in a list of strings and converts them to lower case.This could also be achieved with a loop in the following way,
l = ["MaN", "Sun", "bUN"]
for string in l:
string = string.lower()
But I personally prefer using map
as its just clear, you see it and realise that it converts the elements of the collection passed into it to lower case plus you don't need to get into the mechanics of writing a loop.Using lambda with reduce()
Reduce is also a higher order function. It takes in a collection and boils it down to one value or reduces it to one value, if you might. Lambda functions are used with reduce in a similar fashion to map.NOTE - reduce needs to be imported from functools.
from functools import reduce
reduce(lambda acc, val: acc + val, [1,2,3,4])
This piece of code gives the output as 10. It simply adds all the value.Now getting down to its specifics, acc over here is a variable that is being used to keep tally of the total, it is an accumulator. acc is the value being returned from the reduce function.
In cases like these, when the accumulator is not passed in by the user, reduce chooses first element of the collection as the accumulator and then starts its iteration from the second item. This would make sense in this use case but in multiple other applications accumulator needs to be passed in.
sentence = "It's a nice day!"
lenght = reduce(lambda acc, x: acc + len(x), sentence.split(),0)
Now, in this example accumulator's value has been passed in as 0 as it won't make sence to have the first word of the sentence as the accumulator.Conclusion
Lambda expressions are extremely useful in functional programming and also to make functions that have to be only used once. Sometimes writing a function with thedef
keyword might be a better option because you won't want to trade off readability. Jumbling a lot of tasks into one lambda expression is not good practice as it only makes the code more obscure.
Caesars Casino and Hotel - Dr. Maryland
ReplyDeleteCaesars 안동 출장안마 Casino 경기도 출장안마 and Hotel · 1,888-GAMBLER - FESTIVAL. 속초 출장샵 FACTORY. 713,794. FINE. 제주 출장안마 717,854. FINDING. 718,914. FINDING. 경산 출장샵