Today we are going to look at the lambda syntax and how we can use it to generate on demand dynamic anonymous function objects. Some examples below.
def square_root(x): return math.sqrt(x)
We can code it like this as well
square_root = lambda x: math.sqrt(x)
Other simple examples
sum = lambda x, y: x + y # def sum(x,y): return x + y
More complex example when the resulting code is more readable and cleaner
 
def map(f, s):
    result = []
    for x in s:
            result.append(f(x))
    return result
def square(x):
    return x*x
vals = [1, 2, 3, 4]
newvals = map(square,vals)
The same with the lambda symbol.
newvals = map( (lambda (x): (x * x)), [1, 2, 3, 4] )
References
 
 
 
 Posts
Posts
 
 
 
 
No comments:
Post a Comment