How and when to use python’s lambda

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:

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:

With lambda:

Head caution though, because readability goes out the window whenever the lambda expression gets to complicated.

When not to use lambda:

2 thoughts on “How and when to use python’s lambda

Leave a Reply

Your email address will not be published. Required fields are marked *