How To Use Lambda Expressions in Python

They may look scary at first but they’re pretty simple

Jonathan Hsu
Nov 27 · 4 min read
Photo by Aarón Blanco Tejedor on Unsplash

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
def traditional_square(n):
return n ** 2
# lambda function to multiply a number by itself
lambda_square = lambda n: n ** 2
print(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.

Additionally, the 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

  • Both functions and lambdas may accept zero, one, or many parameters. In a lambda expression, simply list your parameters after the lambda keyword, 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 return keyword.
  • 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?

Refactoring “one-liner” functions to lambda notation

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.

2. The .sort() list method

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[1]) # sort by 2nd value in tupleprint(scores)
"""
[
("Erik",19),
("Jade",21),
("Sylvando,39),
("Rab",110))
]

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 int[1] is used to order the tuples.

3. The filter() function

scores = [("Jade",21),("Rab",110),("Sylvando",39),("Erik",19)]result = filter(lambda t: t[1] > 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 .sort() method, 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>.


Conclusion

Better Programming

Advice for programmers.

Jonathan Hsu

Written by

I’m a black belt problem-solver (literally). I enjoy the taking on new challenges, building skills, and sharing what I’ve learned. 🥋

Better Programming

Advice for programmers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade