Lambda function or anonymous function in python

Lambda function or anonymous  function in python

Lambda Function:

  • ‌They are defined using the lambda keyword and not using the def keyword

  • ‌Lambda functions are a throw-away function

  • ‌They can be used anywhere a function is required

  • They contain a comma-separated list of arguments and the expression is an arithmetic expression that uses these arguments

  • ‌Lambda functions can be used in regular functions

  • Lambda function can be called from another lambda function, called nested lambda function however, use of nested lambda function must be avoided (with nested lambda, recursion can occur and may result in Runtime Error : maximum recursion exceeded error)

Syntax of Lambda Function in python

lambda arguments: expression

Lambda functions can have any number of arguments but only one expression. The expression is evaluated and returned.

sum = lambda x , y : x + y
Print("sum: ", sum(2,3))

// Output: 5

lambda functions can be used without assigning it to a variable

print((lambda x : x*2) (6))

// Output: 12

Lambda arguments can be passed to a function

def fun(a,b):
    Print(a(b))
two = lambda x: x*2
Three = lambda x: x*3
fun(two,7)
Fun(three,2)

// Output: 14, 6

‌they are used along with built in functions like filter(), map(), reduce(), etc

lists = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
greater_than_five = filter (lambda x: x > 5, lists) 
print(list(greater_than_five))

// Output: [10, 8, 7, 11]
lists = [1, 2, 3, 4, 5]
sqr_val = map (lambda x: x*x, lists) 
print(list(sqr_val))

// Output: [1, 4, 9, 16, 25]
from functools import reduce
lists = [1,2,3,4,5]
product = reduce (lambda x, y: x*y, lists)
print(product)

// Output: 120

Key points:

  • Lambda functions have no name

  • Lambda functions can have any number of arguments.

  • ‌Lambda function does not have an explicit return statement but always contains an expression that returned

  • They are a one-line version of a function and hence cannot contain multiple expressions

  • They cannot access global variables, they can access the variables that are only in their parameter list

  • Lambda functions can be passed as arguments in other functions