There is a long running debate in python land of the usefulness of the lambda function, and I usually air on the side of avoidance. However, for simple occasions it can make for cleaner code.
The python docs are essential for quick reference, but sometimes they skimp on obscure features. Lambda is one of those features.
In a nutshell, lambda is the inline function creator for python. In other languages, inline functions often look like this:
1 |
myFunction = function(arg1,arg2) { return arg1+arg2 } |
myFunction is a function, and myFunction(1,2)=3. That makes a lot of sense! myFunction can similarly be defined in python using lambda:
myFunction = lambda arg1,arg2: arg1+arg2
It’s true that this syntax requires less typing, but at the cost of readability. In case you were wondering, here is a good example of when to use it.
Without lambda:
1 2 3 4 |
def isLessThanFour(x): return x<4 list_full = [1,2,3,4,5] list_subset = filter(isLessThanFour, list_full) |
With lambda:
1 2 |
list_full = [1,2,3,4,5] list_subset = filter(lambda x: x<4, list_full) |
Head caution though, because readability goes out the window whenever the lambda expression gets to complicated.
When not to use lambda:
1 |
reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) |