DEV Community

Patrick Hanford
Patrick Hanford

Posted on

5 2

What are lambda expressions in Python?

What are lambda expressions?

lambda expressions in Python are best described as single-use anonymous functions. What I mean by this, can be explained with a quick example.

[1,2,3,4,5]
Enter fullscreen mode Exit fullscreen mode

I have this list of numbers that I want to square (multiply by itself). I could create a function like so.

def square(number):
    return number*number
Enter fullscreen mode Exit fullscreen mode

This works fine, but what if you only need to do this one time? It would be a little cumbersome to have a function dedicated to this pretty menial task. We can use a lambda express for this instead.

lambda number: number*number
Enter fullscreen mode Exit fullscreen mode

So you can see what's happening by referencing the above function next to our lambda expression. We declare lambda so the interpreter knows this is a lambda express. The first item is then the parameter which replaces the number argument in the square() function. Next is the actual result of the expression, number*number.

Here's an example using map() to get the squared result of each number in our list.

list(map(lambda number: number*number, numbers))
> [1,4,9,16,25]
Enter fullscreen mode Exit fullscreen mode

I hope this is a good example to help you grasp lambda expressions so you can avoid huge pages of disposable functions!

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (3)

Collapse
 
vuurball profile image
vuurball

don't forget to pass the numbers to the map()

list(map(lambda number: number*number, numbers))

Collapse
 
codespent profile image
Patrick Hanford

Ah ha, good catch!

Collapse
 
dustyh profile image
Dustin

Thank you, this was a good refresher from what I learned earlier in the year

Image of PulumiUP 2025

Let's talk about the current state of cloud and IaC, platform engineering, and security.

Dive into the stories and experiences of innovators and experts, from Startup Founders to Industry Leaders at PulumiUP 2025.

Register Now

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay