DEV Community

Cover image for Python Lambda expression
Damon Marc Rocha II
Damon Marc Rocha II

Posted on

Python Lambda expression

I recently re-discovered python's version of anonymous functions, lambda, and have been happily using it again as much as possible. Lambda is useful in making your code more concise and allows for brevity when using methods such as map and filter. So what is lambda exactly

What is Lambda Exactly and why use it

Lambda is a method of writing simple functions in a one-liner fashion that can be used in so many different ways.

def square(num):
    return num**2
#or 
def square(num): return num**2
Enter fullscreen mode Exit fullscreen mode

The function above is a prime candidate for lambda, due to the ease in writing it on one line. Since most functions have a return value and will have the def keyword when using lambda these parts of the function declaration are done for you. So the function above can be written as:

lambda num:num**2
#or
t = lambda num:num**2
Enter fullscreen mode Exit fullscreen mode

So the question here is why should you care? Well for example when using it with map, instead of having to declare a small function in your code and then using said function to modify a list, you can do this:

lst = [1,2,3,4,5]
list(map(lambda num:num**2,lst))
#[1, 4, 9, 16, 25]
Enter fullscreen mode Exit fullscreen mode

Do you see the beauty in this? In two lines of code, I declared a list and then squared its elements; I could then print them out or save them to a new list, the possibilities are endless. Another awesome use for lambda is the filter method

Another Awesome Use of Lambda

When using the filter function with lambda filtering out lists and sets can easily be accomplished on one line.
So, for example, let's say I wanted to filter out the list above to only include numbers greater than 2:

list(filter(lambda num:num>2, seq))
#[3,4,5]
Enter fullscreen mode Exit fullscreen mode

Again using lambda I accomplished this in one line, and with that, I will leave you with one question. Could you imagine using this with a large dataset, and easily filtering all the data in one line of code? :)

Top comments (0)