Lambda functions are one line functions!
In [2]:
f = lambda x: (x*2)+5
f is now a function takes one argument x, computes (x*2)+5 and returns it
In [7]:
print type(f)
print f(10)
Lamba functions make it possible to write compact code. As an example, consider the map() builtin function. This returns the result of applying a function on a sequence. Using lambda functions, we can quickly substitute small functions.
In [10]:
l = range(5)
map(lambda x: x*x, l)
Out[10]:
Similarly, there is a filter() function. This evaluates a function on every element of a list. If the evaluated function returns True, then the element is kept in the result list. Else, it is dropped.
As an example, Let's find numbers less than 10, whose squared value is more than 9.
In [11]:
filter(lambda x: x*x>9, range(10))
Out[11]:
The reduce() builtin function applies a binary function from left-to-right, and returns the cumulative result
In [15]:
reduce(lambda x,y: x+y, range(10)) # 10*10-1/2 = 45
Out[15]:
The above expression computes (((((((((0+1)+2)+3)+4)+5+6)+7)+9)