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:
            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
  1. http://pythonconquerstheuniverse.wordpress.com/2011/08/29/lambda_tutorial/
  2. http://python-history.blogspot.co.uk/2009/04/origins-of-pythons-functional-features.html

No comments:

Post a Comment