What's All the Fuss About `lambda` Functions in Python?
Python's `lambda` functions are seemingly obscure, until they aren't. They're almost mystical, until unveiled. Let's shed some light to dispel the obscurity and lift the mystique.
One of my favourite aphorisms I often use when teaching is the following:
Everything is hard when you don't know it. Everything is easy when you know it.
This feels like it ought to be a quote from someone important, but GPT couldn't find any references. So, I think I may have made this up myself. If you like it, I'll take credit. If you think it's silly, it's probably someone else's!
Python's lambda
functions are a perfect example of this idea. Almost everyone finds them puzzling and impenetrable the first time they encounter them. And the second. And third. But I recall the moment I finally understood them, and I remember clearly the thought that streamed through my head:
Is that it? What's all the fuss, then?
They're useful. But they're not magical, even if you may get that impression from how some talk about them.
In this spirit, I'm writing a concise, matter-of-fact article about lambda
functions. The article style mirrors their functionality without glorifying them excessively.
If you're new to my articles, this is not how I usually write my articles!
Allow me a short note about The Python Coding Place. Members of The Place get access to everything I do: video courses ranging across several levels, weekly videos about interesting Python topics, The Place’s members’ forum, and live sessions and cohort courses. Ah, and full access to this substack, too.
Lambda functions are functions. So far, this looks easy, right?
It says it in the REPL/Console output above. So it must be true.
Let's compare a lambda
function with a standard function. And we'll do this with the most boring function you can imagine. The remaining examples are shown in a script rather than the REPL/Console:
Here's a brief animation highlighting the similarities and differences between the two:
And here's the comparison in a table:
You can call a function, whether it's a standard function or a lambda
function. You won't call the function directly in many use cases for lambda
functions. You'll see why later. But it's a function, so you can call it:
With standard functions, you use the function name followed by parentheses to call the function. But lambda
functions don't have a name! Instead, you enclose the expression in parentheses, and you can treat it just like you would treat a standard function name: add (10)
to call the function with 10
as the argument.
You could name a lambda
function if you really wanted to. But if you feel the need to name a lambda
function, you probably should use a standard function instead. Anyway, here's how you would name a lambda
function if you're stubborn enough to do so:
And that's all there is, really. Python's lambda
functions are just functions with no name. You can define them with one or more parameters (or none). However, you can only have a single expression that evaluates to a value. This is the value returned by the lambda
function. Therefore, you can't have complex algorithms in a lambda
function, just whatever you can fit in a single expression!
Here are a few more examples of lambda
functions. There's one with no parameters, one with two parameters, and another with three:
So, when do you need to use a lambda
function? Well, you never need to use one. You can always use a standard function if you wish. But there are cases when it's convenient to use an inline anonymous function rather than define a standard function, think of a good name to give it, and then use it once.
Functions can be used as arguments for other functions. This is especially common in the functional programming style. Here's one example using the built-in map()
function. I'll demonstrate both scenarios: using a standard function and using a lambda
function.
I'll use this dictionary in the following examples:
These are the scores these students got in a test. Let's figure out who passed the test. The pass mark is 5 out of 10.
First, let's use a standard function definition:
Each key in the dictionary scores
is passed to check_pass()
, and the function's return value is used as the output.
Why are the dictionary keys passed to the function and not the key-value pairs? Iteration over dictionaries in Python uses the keys. This is also the case if you use a dictionary in a for
loop, say.
Next, using a lambda
function:
You get the same result. It's more convenient to use lambda
functions in these scenarios.
I can't conclude this section without pointing out that there's another way to obtain the same result, which many would consider preferable and more Pythonic:
Use lambda
functions if you want. Don't if you don't! And this brings us to the end of this short article. Python's lambda
functions are functions with no name and which have a single expression. They're "disposable" functions. You create them as and when you need them, and then they're gone.
And at under 1,000 words, this is one of the shortest articles I ever wrote!
Code in this article uses Python 3.12
Stop Stack
#42
I'm getting closer to the official launch of The Python Coding Place (15 January 2024). There are already many who joined as lifetime members, and I hope many more will join over the coming weeks and months to grow this new community into a thriving learning platform for beginners and intermediate Python programmers. There are video courses, weekly videos, members' forum, live workshops, and even cohort-based courses…all included in the lifetime membership.
Read more about The Python Coding Place membership here
Recently published articles on The Python Coding Stack:
In Conversation: Pawel and Stephen Discuss Matplotlib's New-ish subplot_mosaic() In recent years, Matplotlib introduced a new function for plotting several plots in one figure. We had a chat about
subplot_mosaic()
In Conversation: Rodrigo and Stephen Discuss Analogies When Learning To Code A conversation between Rodrigo Girão Serrão and Stephen Gruppetta on analogies in programming
A Touch of Randomness Makes The Magic Sparkle • A Python
turtle
Animation Let's build this sparklyturtle
animation step by stepNumPy for Numpties Introducing an infrequent, loose series of articles on NumPy
The Curious Little Shop at The End of My Street • Python's f-strings Many people's favourite Python feature: f-strings
Recently published articles on Breaking the Rules, my other substack about narrative technical writing:
I Haven't Been Abducted by Aliens (Ep. --) Why this long lull since the last Breaking The Rules post?
The Selfish Reason (Ep. 13) Another reason for authors to innovate • Enjoying the writing process
The Consequential Detail (Ep. 12). Can a single letter or one blank line make a difference? (Spoiler Alert: Yes)
The Unexpected Audience (Ep. 11). What I'm learning from listening to Feynman's physics lectures
The Story So Far (Mid-Season* Review). Are you back from your holidays? Catch up with what you've missed
Stats on the Stack
Age: 7 months, 2 weeks, and 5 days old
Number of articles: 42
Subscribers: 1,470
Each article is the result of years of experience and many hours of work. Hope you enjoy each one and find them useful. If you're in a position to do so, you can support this Substack further with a paid subscription. In addition to supporting this work, you'll get access to the full archive of articles and some paid-only articles. Alternatively, if you become a member of The Python Coding Place, you'll get access to all articles on The Stack as part of that membership.
This was just fantastic as usual, thanks stephen!
Excellent as usual! Just for the sake of fun, you definitely *can* program *anything* using just lambdas. They're Turing-complete! Now, whether you should...