Lambda

  • A function is defined without name is said to be Lambda function or anonymous function.
  • It can take any number of arguments, but can only have one expression.
Syntax

lambda arguments : expression

Single argument

#squrt function

x = lambda a : a*a

print(x(5))

Multiple argument

x = lambda a,b : a*b

print(x(5,6))

Lambda with built-in

Lambda functions are used along with built-in functions like

  • filter()
  • map()
  • Reduce()

Filter

The filter() function in Python takes in two arguments- lambda function and the list which needs to be filtered.

li = [5, 7, 20,66,58,99,63,44]

final_list = list(filter(lambda x: (x%2 != 0) , li))

print(final_list)

Map

  • The map() function in Python takes in two arguments- lambda function and a list
  • This returns a new list which contains all the lambda modified items of the original list.
li = [22,58,66,2,4,8,9,64]

final_list = list(map(lambda x: x*2 , li))

print(final_list)

Reduce

  • The reduce() function in Python takes in two arguments- lambda function and a list.
  • This returns a new reduced result by performing an operation repetitively over the pairs of the list until single result is achieved.
from functools import reduce

li = [1,2,3,4,5,6,7]

sum = reduce((lambda x, y: x + y), li)

print (sum)

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *