How To Use Lambda Expressions in Python
They may look scary at first but they’re pretty simple
Lambda expressions always freaked me out. I’m not sure why… I think the name — honoring Alonzo Church’s introduction of lambda calculus—makes them sound complex or too “mathy”.
Or, maybe it’s because I had not come across a good use case to learn why they are necessary.
The term anonymous function/expression also used to throw me off. Does it behave differently than a normal
def function? What are the pros/cons of them? How do lambdas fit in?
How I Came to Understand Lambdas
It helped my learning to throw out the anonymous aspect of lambdas and start to understand them as a condensed syntax for writing simple functions.
Let’s take a quick look at a traditional function converted to a lambda expression.
# traditionally defined function to multiply a number by itself
return n ** 2# lambda function to multiply a number by itself
lambda_square = lambda n: n ** 2print(traditional_square(5)) # 25
print(lambda_square(5)) # 25
All we’ve done is re-arranged some of the components and cleaned up unnecessary syntax. Instead of using
def to define a function, the word
lambda is used, which is immediately followed by the parameter list.
return keyword is omitted, further condensing the syntax. Lastly, while the definition is anonymous, we store it to the variable
lambda_square, effectively naming it.
Similarities and Differences Between Functions and Lambdas
Now that we’ve cleared up the basic syntax of lambdas by relating them to traditional function definitions, let’s go over some of the key similarities and differences between the two.
- Both functions and lambdas may accept zero, one, or many parameters. In a lambda expression, simply list your parameters after the
lambdakeyword, separated by commas.
- Lambdas are technically expressions, thus they can only contain other expressions within their body. This should help make sense of why lambdas do not use the
- Only functions can have multiple lines. Technically, a lambda can be written across multiple lines using a backslash (
\); however, the essence of the bullet is that only functions can have multiple statements, effectively doing more than one thing. Lambdas are limited to a single expression in the body.
When Do I Use Lambdas?
There are three opportunities to begin weaving lambda expressions into your programming practice.
Refactoring “one-liner” functions to lambda notation
This is the lowest hanging fruit and a good way to get comfortable with the syntax.
For functions that are already single statements or can be reduced to a single statement, try to rewrite them as a lambda expression, similar to what I showed above.
.sort() list method
There’s nothing special about
.sort() compared to other methods that accept lambda expressions; this has just been a common use case in my experience.
In a list of primitive values — think integers or strings — the list will naturally be sorted by value.
scores = [54,36,75,85,13,46]scores.sort()print(scores) # [13,36,46,54,75,85]
But what about complex data types such as tuples, dictionaries, or classes?
You can use lambda expressions to specify how you’d like to perform the sort.
scores = [("Jade",21),("Rab",110),("Sylvando",39),("Erik",19)]scores.sort(key=lambda t: t) # sort by 2nd value in tupleprint(scores)
In the example above, we define the key to sort by as the result of our lambda expression. Each item in the list is set to
t and the value in
t is used to order the tuples.
.sort(), this function takes a function as the first argument. The second argument is an iterable such as a list. Taking the same list of tuples from above, we can create a filtered iterator.
scores = [("Jade",21),("Rab",110),("Sylvando",39),("Erik",19)]result = filter(lambda t: t > 25, scores)print(list(result)) # [("Rab",110),("Sylvando",39)]
There are a few nuances with the
filter() function that I want to clarify.
The result of the function is stored in a variable
result because unlike the
filter() does not modify the original data.
The need to create a list is because a filter object is returned that points to the filtered version of the iterator. If we try to print without creating a list, the output will be something like
<filter object at 0x7f3fb03ce7d0>.
I hope this introduction to lambda expressions helps take away some of the fear and apprehension. If you have other examples of simple lambdas that helped you get over the hump then please share them!