Python Lambda Functions

  • Lambda function is a function without a name.
  • Lambda function is also known as an anonymous function.
  • They are defined using lambda keyword.
  • Lambda functions are used extensively along with built-in functions like filter(),map(), reduce().
  • It is a function but we use “lambda” keyword instead of “def” to define it.

Syntax Of Lambda Function:

Syntax:

lambda inputExpression: ReturnExpression

Lambda Function Example:

Example:

Now let’s see how to implement the lambda function. Python code to find cube of a number. Here we are stroing return value on cube variable.

cube = lambda x:x**3
x = 20
print(cube(x))

Output:

8000

Example:

Similar cube function implementation with “def” keyword.

def cube(data):
    return data**3

x=20
print(cube(20))

Output:

8000

Lambda & Filter Function:

Example:

Lambda function with filter function.

fruit = ["Apple","Banana","Pear","Apricot","Orange"]

fruitFilter = filter(lambda Str:Str[0]=="A",fruit)
print(list(fruitFilter))

Output:

['Apple', 'Apricot']

Lambda & Reduce Function:

Example:

Lambda function with reduce function.

from functools import reduce
list01 = [2,4,7,3]
print('Sum: ',reduce(lambda x,y:x+y,list01))

Output:

Sum: 16

Lambda & Map Function:

01. Example:

How to implement the lambda function for mutiple inputs. This method also work for more than two inputs. (map function)

val= [10,20,30,40,50]
indx = [1,2,3,4,5]

list01 = list(map(lambda x,y:x**y,val,indx))
print(list01)

Output:

[10, 400, 27000, 2560000, 312500000]

02. Example:

Lambda function with map function. It will perform square of each element of list1.

list1 = [1,5,8,2,3,10,15]
print(list(map(lambda x:x**2,list1)))

Output:

[1, 25, 64, 4, 9, 100, 225]

 

Leave a comment