Lambda Functions OR Anonymous Functions in Python

Spread the love

Lambda or anonymous functions are so called because they are not declared as other functions using the def keyword. Rather they are created using the lambda keyword. Lambda functions are throw-away functions i.e. they are just needed where they have been created and can be used anywhere a function is required.

Lambda functions contains only a single line. It’s syntax is given below.

lambda arguments: expression

The arguments contains a comma separated list of arguments and the expression is an arithmetic expression that uses these arguments. The function can be assigned to a variable to give it a name.

sum = lambda x, y: x + y
print('Sum = ', sum(5, 10))
Sum =  15

In the above code, the lambda function returns the sum of its two arguments. In the above program, lambda x, y: x + y is the lambda function. x and y are the arguments and x + y is the expression that gets evaluated and returned. Note that lambda function has no name. It returns a function object which is assigned to the identifier sum.

The above lambda function can be written as

def sum(x, y):
    return x + y

Things to Remember –

  • Lambda functions have no name
  • Lambda functions can take any number of arguments.
  • Lambda functions can return just one value in the form of an expression.
  • Lambda function definition does not have an explicit return statement but it always contains an expression which is returned.
  • They are a one-line version of a function and hence can not contains multiple expressions.
  • They can not access variables other than those in their parameter list.
  • Lambda functions can not even access global variables.
  • You can pass lambda functions as arguments in other functions.
def small(a, b):
    if (a < b):
        return a
        return b

sum = lambda x, y: x + y
diff = lambda x, y: x - y
# pass lambda functions as arguemnts to the regular function
print("Smaller of two numbers: ", small(sum(5, 10), diff(12, 13)))
Smaller of two numbers:  -1
  • You can use lambda functions in regular functions.
def increment(y):
    return (lambda x: x + 1)(y)

a = 100
print('a : ', a)
print('a after incrementing: ', increment(a))
a :  100
a after incrementing:  101
  • You can define a lambda that receives no arguments but simply return an expression.
x = lambda: sum(range(1, 10))
# invoke lambda function
  • The time taken by a lambda function to perform a computation is almost similar to that taken by a regular function.

Rating: 1 out of 5.

Leave a Reply