Learn to Love Your Lambda!
Lambda functions in python are simple one-line functions without a name (and therefore called an anonymous function) that can take many arguments but will only evaluate a single expression. They’re fast, short, and simple and can help you write cleaner ‘more pythonic’ code.
If like me you wanted to learn lambdas as a newbie python programmer and you were lucky, the above text is an example of what your Google search might deliver. Abstract, a bit jargon-y for the beginner but not too obscure. However, if you were unlucky and went straight to source in the python documentation you got this:
While this explanation makes sense to me now, for a newcomer to python, explanations such as these filled with jargon are seriously not helpful. In this article I want to step gently into lambda functions for those who need a clearer explanation, without too much jargon, on how to construct them, when they might be useful, and why.
But First – Why Lambda?
So named after the 11th letter in the Greek alphabet, those of you who are mathematical geeks will know that American mathematician Alonzo Church invented lambda calculus during his studies into the foundations of mathematics in the 1930s, and it was he that chose to use the letter as a descriptor. At one point Guido van Rossum, the gentleman who created python, was planning on removing the lambda function from the new python 3.0, however it survived and remains available to us. Given we still have it, best we know how and when to use it.
The ‘Classic’ Python Function
As a new coder, you rapidly get to understand that functions are an effective rinse-and-repeat way of executing a particular task. A way of being more efficient with your time by designing a series of steps you wish to execute, calling that sequence a name and then simply calling that name later on in your code while passing it an argument, rather than writing out the same sequence multiple times.
The following code shows the definition of a function that will accept a variable ‘age’ and return one of two different responses, depending on whether the person is over 18 or not. We then call the function and return an answer.
def age_verification(age): if age < 18: return 'Junior' else: return 'Adult' print(age_verification(12)) # Junior
Simple enough and self explanatory. But assuming you only needed to do the age check once in your program it is a bit of overkill to use six lines of code to make a simple yes or no decision.
Lambda Function Basics
In this situation lambda functions become useful. Before we solve the above, let’s take a look at the construction of a lambda function and once we know how they are put together we’ll come back to the adult_verification example above and see how we might use a lambda function to tidy that up.
When I first started coding, I really struggled to understand the make-up of a lambda. It just didn’t make sense for me at that time and it wasn’t until I stumbled across a simple drawing that everything fell into place for me. I’ve reconstructed the drawing below which, while at risk of belabouring the point, compares the components in a function to those in a lambda. The function ‘name’ (red), the argument (green) and the expression (yellow). If there is anyone else out there who, like me, just didn’t get it at first – I hope this diagram helps demystify things somewhat.
As you can see in the code above, to write a lambda you must use the word lambda followed by the number of arguments you intend to process. You then type a colon, a space and then the ‘expression’ or the actions you wish to enact on the arguments.
In the following example we’ve used only one argument, x. The expression multiplies x by 2 and adds 42. We pass 5 to the expression using the print function which, once evaluated, returns 52.
a = lambda x: x * 2 + 42 print(a(5)) # Prints 52
Let’s add some more arguments:
z = lambda a, b, c: 2 * a + b – c print(z(10, 4, 2)) # Prints 22
Applying the Lambda
Simple yes? So now you see the structure of a lambda, let’s try and apply one to the adult_verification example we used earlier. We know we have one argument, that of age, and the expression then needs to evaluate whether the age is less or greater than 18.
First the defined function from our previous example.
def age_verification(age): if age < 18: return 'Junior' else: return 'Adult' print(age_verification(12)) # returns Junior
If we rewrote this function as a lambda, it might look like the following.
a = lambda x: 'Adult' if x > 18 else 'Junior' print(a(12)) # returns Junior
When I ran these two functions, I also ran a timer to understand the execution time of each.
- Function execution time: 3.207399999999305e-05
- Lambda execution time: 1.0905000000005494e-05
So given this scenario, here are the benefits of the lambda as I see them.
- Six lines of code reduced to two
- No need to name the function as it won’t be used again
- No need to ‘return’ a value with a lambda, it is implicit in the lambda function
- Clean concise code being less verbose than the defined function and arguably easier to read
- Faster! From the execution times above we see the lambda is three times faster
Things to Remember
It is worth remembering that lambda functions are defined above as ‘simple one line functions’. While that means you can’t use multi-line expressions, conditional expressions such as if/else are possible when the syntax is written correctly as you saw above.
You unlock greater power when you combine other python built-in functions with the lambda. These include filter() and map() if you wish to iterate through and act upon elements in lists, dictionaries, tuples or sets.
- Using a lambda with
map()will apply the function to each element in turn;
- Using a lambda with
filter()will return the elements satisfying the condition expressed
Here are two examples using map() and filter().
lst = [11, 12, 13, 14, 15, 16, 17, 18] # Use map() to carry out an action on each item in lst amended_list = map(lambda x: x * 2 - 16, lst) print(list(amended_list)) # Returns [6, 8, 10, 12, 14, 16, 18, 20] # Use filter() to extract the elements in lst meeting the condition over_15 = filter(lambda x: x > 15, lst) print(list(over_15)) # Returns [16, 17, 18]
Just Because You Can – Doesn’t Mean You Should!
For those of you who know about photography, when High Dynamic Range (HDR) techniques became mainstream in the photographic world, everyone jumped on the bandwagon and began pushing out photos which were HDR’d to death, overblown, dreadful to look at and totally unnecessary. Similarly, when you first learn and understand lambda functions in python, you fall so much in love with them that you’ll believe there is no problem you can’t solve with a lambda.
Here’s the thing; while there is no doubt they can make your code easier to read, they can also make it more incomprehensible. Their use can make you look like you know what you’re doing as a coder, but they can also mark you out as a novice when used unnecessarily. While undoubtedly providing a fast and easy way to solve an immediate problem, but there may be more readable methods of achieving the same result in a single line.
The bottom line is to think of those following along behind who may need to read your code. I have two rules-of-thumb for using lambdas.
- Is the use of a lambda function the quickest method of solving a problem? If writing the lambda becomes quite complex or requires considerable thought, it may be better to define a normal function and use that instead.
- How readable (or obscure) does the lambda function make your code. It may seem fine to you while the code is ‘uploaded’ in your head and you understand it well. It may not be so obvious weeks, months or even years later when others need to make sense of your intent. Normal functions have a name designed to make clear the intention of the following code. Lambdas, being anonymous, don’t have that utility and it can be difficult to immediately grasp intent.
So There You Have It
This article is designed to introduce new coders to the delights of the lambda function. There is more to be said and more complex issues to understand, however you can use this as a jumping off point to experiment with. Use lambdas sparingly and they will help you write cleaner, faster, more ‘pythonic’ code. Truth be told, there is a sense of achievement when you manage to solve in one-line what once would have used many.
David is a Python programmer and a technical writer creating in-depth articles for readers wanting uncomplicated explanations for topics made difficult by industry jargon. Also a woodworker, metalworker, landscape photographer, and pilot, he is freelance after 42 years in the corporate world. He has an MBA in Technology.