top of page
  • Writer's pictureAdmin

Lambda : Anonymous Function

In Python, there is an anonymous function which is defined by the help of lambda  keyword, the syntax of the  lambda  function is:


lambda parameters : expression


Let's take an example, assume we have following list of animals:


animals = ['dog', 'cat', 'cow', 'horse', 'deer', 'lion', 'monkey']


Now let's say we have to filter our list to print only the name of the animals which are 

3 characters long.  We can do this by defining a function which can compare word lengths, and then passing it to a built-in function  filter() :

def three_letter_names(name):
     if len(name) == 3:
         return True
         
three_letter_names = filter(three_letter_names, animals)

for animals in three_letter_names:
    print(animals)


The output of the above code will be:

dog 
cat 
cow 
>>>


So, we can perform the same task directly in filter() using lambda expression without defining a separate named function:

animals = ['dog', 'cat', 'cow', 'horse', 'deer', 'lion', 'monkey']

three_letter_names = filter(lambda name: len(name) == 3, animals)

for animals in three_letter_names:
    print(animals)


The output of the above code is same:

dog
cat
cow
>>>


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

So, this:

add = lambda x,y: x+y 
print(add(2,2))


is equivalent to this:

def add(x,y):  return x + y print(add(2+2))










3 views0 comments

Recent Posts

See All
bottom of page