DEV Community

Cover image for Python: What is a Lambda Function?
Adam Lombard
Adam Lombard

Posted on • Edited on

Python: What is a Lambda Function?

In Python, the lambda keyword is used to define an anonymous (i.e., nameless) function, using the following syntax:

lambda parameters: expression 
Enter fullscreen mode Exit fullscreen mode

Assume we have the following list of fruits:

fruits = ['apple', 'orange', 'grape', 'lemon', 'mango', 'banana'] 
Enter fullscreen mode Exit fullscreen mode

Now imagine we need to filter our list to print only fruit names which are 5 characters long. We could do so by defining a named function to test word lengths, and then passing it (and our list of fruits) to filter():

def five_letter_words(word): if len(word) == 5: return True five_letter_fruits = filter(five_letter_words, fruits) for fruit in five_letter_fruits: print(fruit) 
Enter fullscreen mode Exit fullscreen mode
apple grape lemon mango >>> 
Enter fullscreen mode Exit fullscreen mode

Or, the same task can be accomplished directly in filter() using a lambda expression, without needing to define a separate named function:

five_letter_fruits = filter(lambda word: len(word) == 5, fruits) for fruit in five_letter_fruits: print(fruit) 
Enter fullscreen mode Exit fullscreen mode
apple grape lemon mango >>> 
Enter fullscreen mode Exit fullscreen mode

Because lambda functions are Python expressions, they can be assigned to variables.

So, this:

add_two = lambda x, y: x+y add_two(3, 5) 
Enter fullscreen mode Exit fullscreen mode

Is equivalent to this:

def add_two(x, y): return x + y add_two(3, 5) 
Enter fullscreen mode Exit fullscreen mode

Was this helpful? Did I save you some time?

🫖 Buy Me A Tea! ☕️


Top comments (1)

Collapse
 
waylonwalker profile image
Waylon Walker • Edited

I learned the lesson of not binding arguments in dynamically created lambdas. I find creating lambdas inside of loops/list comprehension so useful, but it is easy to end up with a list of lamdas that all return the final result.