lambda Function in Python

They are basically anonymous function. A lambda expression starts with the word lambda then followed by a parameter list, after colon we write expression that function will operate on and return. It can have any number of arguments but only one expression, which is evaluated and returned. It must have a return value.

They are more readable as we don’t scroll to find its definition.

Example:

x=2
anon=lambda x: x*2

def double(x) :
      return x*2

print(anon)
print(double)

Output:

<function <lambda> at 0x152e907951f0>
<function double at 0x152e90630ca0>

In order to call both function send one positional parameter as argument to function.

x=2
anon=lambda x: x*2

def double(x) :
      return x*2

print(anon(2))
print(double(2))

Output:

4
4

Difference between a lambda function and a regular function:

lambda Function

  • This function does not have any name
  • As lambda is an expression so we can use it anywhere that an expression can appear. A lambda expression evaluates to a function and that function is then used as value of expression.
  • lambda can only contain single expression
  • Ideal for short one time use operations

def defined function

  • The function has got a name

  • This function can contain many lines of code
  • It is better suited for more complex and reusable code

Conditional Expressions:

A conditional expression (also known as a ternary operator) allows you to evaluate a condition and return one of two values based on the result.

Syntax: <true value> if <condition> else <false value>

If the condition is true , true value will be returned else false value will be returned.

Note: A conditional expression can be any- number, string, function or any complex expression.

lambda with conditional expression:

Since a lambda function must have a return value for every valid input, we cannot define it with if but without else as we are not specifying what will we return if the if-condition will be false i.e. its else part.

Example:

max = lambda a, b: a if(a>b) else b 
print(max(1, 2))
print(max(10, 2))

Output:

2
10

Here post lambda we have defined the two parameters and post colon this parameter value will be evaluated using conditional expression and accordingly the value will be return.

One more example:

square= lambda x: x*x if(x>0) else None

print(square(4))

Output:

16

Leave a Reply

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