Python Lambda (Anonymous) Functions

In this article, you'll learn about the lambda functions in Python with the help of examples.

In Python, lambda functions are single-line functions defined without a name. Hence, lambda functions are also called anonymous functions.

It is important to understand how the Python function works to understand Lambda functions.


Python Lambda Function Syntax

We use the lambda keyword to define lambda functions.

lambda arguments: expression

Unlike a normal function defined using the def keyword, a lambda function can have any number of arguments but can only have one expression.


Example: Python Lambda Function

# lambda function
double = lambda n: n * 2

# prints lambda function
print(double(10)) #20

The above function has no name. It returns a function object which is assigned to the double variable.

  • x - argument
  • x * 2 - return value of the function (expression)

We call the lambda function using the variable it is assigned to:

print(double(10))

Note: The above lambda function:

double = lambda n: n * 2

is equivalent to

def double(n):
    return n * 2

print(double(10))

Example: Print Larger Number using Lambda Function

We can use if...else with the lambda function. For example,

larger = lambda a, b: a if a > b else b

print(larger(10, 47)) # 47

This lambda function takes two arguments a and b. It returns a if a is larger than b; otherwise, it returns b. The if...else part is the conditional expression that makes this possible.

Note: This use of a lambda function is very much like a condensed version of the following traditional function:

def larger(a, b):
    if a > b:
        return a
    else:
        return b

Use of Lambda Function in Python

In Python, we use the lambda function as an argument to a function that takes other functions as arguments. Lambda functions are used along with built-in functions and methods like sort(), filter(), map() etc.

We can use the lambda function with the sort() function as a key to sort the list in a custom way.

names = ['Alan', 'Gregory', 'Zlatan', 'Jonas', 'Tom', 'Augustine']

names.sort(key=lambda x: len(x))
print(names)

Output

['Tom', 'Alan', 'Jonas', 'Zlatan', 'Gregory', 'Augustine']

Here, the names are sorted on the basis of the length of the list instead of the alphabet. This is because the sort() function uses the length of each string as the key while sorting.


Example: Lambda Function With map()

my_list = [1, 5, 42]

new_list = list(map(lambda x: x * 3 , my_list))

print(new_list) # [3, 15, 126]

We have used lambda expression with map() function to triple values of all the items in a list.

The map() function applies a function to every item in a list and returns a map object. The function we are mapping over my_list is lambda x: x * 3, which takes an argument x and multiplies it by 3.

Recommended Reading: Python Functions

Did you find this article helpful?