written by Eric J. Ma on 2020-05-17 | tags: python programming lambda expression
Inspired by a conversation I had with a colleague who is learning Python, I wanted to write down an explainer of what "lambda expressions" are in Python.
You might have seen lambda expressions in someone else's Python code, which looks like such:
lambda x: x % 2 == 0
This, actually, is the equivalent of writing a function that we might name is_even
:
def is_even(x): return x % 2 ==0
Here's an explainer of the anatomy of the lambda function.
lambda
tells Python that we're constructing a function.lambda
and :
. In our example, the signature of the function is x
, meaning the function only takes in a single argument, x
.:
. In our case, it's the boolean result of x % 2 == 0
.So a lambda function basically equivalent to a Python function. The key difference here is that it is considered "anonymous", in that we have not given it an explicit name.
Let me explain. When we use the following pattern:
def func_name(arg1, arg2): return something
the function has a name, given by func_name
.
However, when we do a lambda function:
lambda arg1, arg2: something
this function doesn't have a name. Hence, the term "anonymous".
But what's the use of a lambda function if all it does is nothing more than be "anonymous"? Well, one place I have used lambda functions is when I determine that a function that I want to implement is a simple one-liner that can get slotted in anywhere. For example, in pyjanitor
, when transforming a column to see whether it's even:
df = data.transform_column("my_column", lambda x: x % 2 == 0, "is_even")
That would be less verbose than:
def is_even(x): return x % 2 == 0 df = data.transform_column("my_column", is_even, "is_even")
RealPython has a great article which also details the appropriate uses of lambda expressions; definitely check it out!
@article{
ericmjl-2020-what-python,
author = {Eric J. Ma},
title = {What are lambda expressions in Python?},
year = {2020},
month = {05},
day = {17},
howpublished = {\url{https://ericmjl.github.io}},
journal = {Eric J. Ma's Blog},
url = {https://ericmjl.github.io/blog/2020/5/17/what-are-lambda-expressions-in-python},
}
I send out a newsletter with tips and tools for data scientists. Come check it out at Substack.
If you would like to sponsor the coffee that goes into making my posts, please consider GitHub Sponsors!
Finally, I do free 30-minute GenAI strategy calls for teams that are looking to leverage GenAI for maximum impact. Consider booking a call on Calendly if you're interested!