Tuesday, December 10, 2013

lambda functions in python

Lambda functions are kind of anonymous functions. It creates functions on the fly. Instead of defining an entire method for the sole purpose of using it once, you can simply define the function right in the parameter list.
Syntax: 
    lambda [parameter_list] : expression

Two notes I want to emphasize: 
1. Function must return something, which is expression highlighted. It is similar to a regular function that returns.
2. By bracketing the whole thing, you can use it as normal function name. See examples below.

For example:
# A regular function
def incrementor(x):
  return x + 1    

print incrementor(3)
print (lambda x: x+1)(3)     #note 1 in red, note 2 is bold

#define a function sayhello
sayhello = lambda x: 'hello ' + x
print (lambda x: 'hello ' + x)('world')
print sayhello('world')

ls=['232', '32e23', '23423', '2de2']
#define a function f1
f1=lambda x: x.find('e') > -1
print filter(lambda x: (x.find('e') > -1 ), ls)
print filter(f1, ls)

No comments:

Post a Comment