Search This Blog

Tuesday, April 16, 2013

Anonymous function in Python

Python is one of the very popular languages, especially when it comes to scripting and  automations. But it is a general purpose language whose syntax is able to express constructs from procedural or object or even functional languages.

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:
    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] )


No comments:

Post a Comment