DEV Community

Patrick Hanford
Patrick Hanford

Posted on

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!

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