Python – Anonymous Functions

Lambda Expression in Python

We would cover anonymous functions. These are functions that you create without the def keyword. You declare then using the lambda keyword. That is why they are also called lambda expressions.

You can review Functions in Python.

 

The following applies to anonymous functions in Python:

  • they can take any number of arguments. However, they return only one value in form of an expression.
  • they cannot contain multiple expressions or commands
  • anonymous functions can only access variables that have been provided in their parameter list

 

How to create an anonymous function

You create a anonymous function using the lambda keyword, then followed by a list of parameters. Then followed by a colon, then the expression.

For example, the code below is a lambda expression that calculates average of three numbers

# lambda expression to calculate average
average = lambda num1, num2, num3: (num1 + num2 + num3)/3

Now you can see that it is just a one-line function. The parameters num1, num2 and num3 are not enclosed in parentheses, as you can see

Let’s now write this same function using the normal def keyword, so we can see the difference

# equivalent function using def
def average(num1, num2, num3):
    return (num1 + num2 + num3) / 3

 

The lambda expression below would print out the total of three numbers.

total = lambda num1, num2, num3: print(num1 + num2 + num3)

 

To use the above function you just call it like every other function. For example, below is a code to call the lambda expression.

total(4,6,7)

If you run this code, then it would call the lambda expression and print out the sum of 4, 6 and 7

 

When to use lambda expressions

Since lambda expressions are just one-line of code, it would not be best write very large and complex functions with them. So you need to decide.