How to Use Lambda in Python

First Python supports Functional Programming, which means you can pass a function to another function to do something.

def subFunc(x):
return x%3 == 0

result = realFunc(subFunc, range(2,20))

Lambda is to replace subFunc with an anonymous function, eg

result = realFunc(lamda x: x%3 == 0, range(2,20))

Second Lambda can be used to replace constant inside a function

def add_const(n): return lamda x: x+n
f = add_const(2)
g = add_const(3)
print f(10), g(10) #result 12, 13

F, G are different function share similar logics.


Leave a comment

Filed under Read

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s