Using lambda functions in python. Defining a lambda function
Lambda functions in python can be somewhat confusing. Here is a brief introduction
Lambda functions are handy functions that can be defined in 1 line, and thrown away afterwards. Here is a small example of what the syntax for a normal function looks like, and what the syntax for a lambda function looks like:
def f(x): return x * x
And here is the same function using the lambda syntax:
f = lambda x : x * x
Lambda functions really come in handy when used with python functions such as filter(), map() and reduce(). Here are some examples.
First we have filter. It will return a copy of a list where the function you pass returns True. This example will return only even numbers (because any number mod 2 will be equal to 0 if it is even).
array = [1, 2, 3, 4, 5, 6] #create an array of integers
print filter(lambda x: x % 2 == 0, array)
Output:
[2, 4, 6] # a list containing all even numbers
Next we will show map. It is basically a mapping of one list to another using a function (or a lambda function):
array = [1, 2, 3, 4, 5, 6] #create an array of integers
print map(lambda x: x * x, array)
Output:
[1, 4, 9, 16, 25, 36] # a list containing squares of 1, 2, 3, etc
And finally we have reduce. What this will do is convert the list into a single value. Our function will add element 0 and element 1. That result is then added to element 3, that result is then added to element 4, etc. Eg. (((((1+2) + 3) + 4) + 5) + 6) = 21
array = [1, 2, 3, 4, 5, 6] #create an array of integers
print reduce(lambda x, y: x + y, array)
Output:
21
And that concludes our short tutorial on creating and using lambda functions
No comments:
Post a Comment