Newby Coder header banner

Python Lambda

Python Anonymous Function

These functions are called anonymous because they are not declared in the standard manner by using the def keyword

Instead, lambda keyword is used to create anonymous functions

They are defined without a name, but are assigned to variables, which can be called like functions

Syntax

The syntax of lambda functions contains only a single statement, which is as follows -

lambda [arg1 [,arg2,.....argn]]:expression 

Following is the example to show how lambda form of function works -

#!/usr/bin/python
# Function definition is here
sum = lambda arg1, arg2: arg1 + arg2

# Now, sum can be called as a function
print("sum of 10, 20:", sum(10,20))
print("sum of 20, 20:", sum(20,20)) 

Output :

sum of 10, 20: 30
sum of 20, 20: 40

Example of Lambda Function in python

Following example shows a lambda function that doubles the input value

>>>double = lambda x: x * 2
>>>double(91)
182

In the above example, lambda x: x * 2 is the lambda function

Here x is the argument and x * 2 is the expression that gets evaluated and returned

This function has no name but returns a function object which is assigned to the identifier double

This identifier can then be called as a function

The statement

double = lambda x: x * 2 

is analogous to

def double(x):
   return x * 2 

Use of Lambda Function in python

Lambda functions are used when a nameless function is required for a short period of time

In Python, it is typically used as an argument to a higher-order function (a function that takes in other functions as arguments)

Lambda functions are used along with built-in functions like filter(), map() etc

Example use with filter()

The filter() function in Python takes in a function and a list as arguments

That function is called with all the items in the list and a new list is returned which contains items for which the function evaluates to True

Following example uses filter() function to filter out only even numbers from a list

>>> y = filter(lambda x: x%2==0, list(range(1, 20)))
>>> list(y)
[2, 4, 6, 8, 10, 12, 14, 16, 18]

Example use with map()

map() function in Python takes in a function and a list

That function is called with all the items in the list and a new list is returned which contains items returned by that function for each item

Following example uses map()function with lambda to get the square of all the items in a list

>>> y = map(lambda x: x*x, list(range(1, 20)))
>>> list(y)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361]