A function that is defined without a name is called lambda function in Python. It usually consists of a one-line expression that shows a function using the lambda construct.
Sometimes, we also call it as an anonymous function in Python. Anonymous function means a function without a name (i.e. nameless function).
In Python, we generally define a normal function with the def keyword, but we define an anonymous function using lambda keyword.
The general syntax to define a lambda or anonymous function in Python is as:
lambda arguments: expression
The following are some key points about lambda functions:
- The number of arguments for the lambda function is infinite, i.e. it can take as many arguments as we want, but it return only one value in the form of expression.
- It cannot have more than one expression.
- It cannot have comments.
- Python interpreter evaluates this single expression, then returned it.
- Lambda function does not include the return statement to return an expression.
- We cannot directly call lambda function to print because lambda needs an expression.
- Lambda functions are not similar to inline functions in C or C++.
Lambda Function Example
Example 1:
Let’s write a program in Python in which we will use the lambda function that squares the value of input.
# Program to calculate the square of a number. squared = lambda num: num ** 2 # lambda function with lambda keyword. print(squared(20)) # function call and prints the returned value on the console.
Output: 400
In the above example program, lambda num: num ** 2 is the lambda function where num is an argument and num ** 2 is the expression that the interpreter evaluates and returns. The variable ‘squared’ holds the function object returned by the expression.
The statement which assigns the lambda expression to ‘squared’ is almost equivalent to defining a normal function named squared with the following statements:
def squared(x): # normal function with def keyword. return x ** 2 # return statement.
Example 2:
Let’s write a program to calculate the sum of three numbers using lambda or anonymous function.
# Program to find the sum of three numbers. sum = lambda n1, n2, n3: n1 + n2 + n3 # Main program. # Take three numbers as input from the user. n1 = int(input("Enter your first number: ")) n2 = int(input('Enter your second number: ')) n3 = int(input('Enter your third number: ')) print('Sum of three numbers =',sum(n1, n2, n3))
Output: Enter your first number: 30 Enter your second number: 60 Enter your third number: 90 Sum of three numbers = 180
In the above program code, we have taken three numbers as input from the user and stored into variables n1, n2, and n3, respectively. Then, we have passed them while calling lambda function.
Inside the lambda function, Python evaluates the expression using argument values and returns the result to the caller.
Example 3:
# Program to find the multiplication of three numbers. multiply = lambda n1, n2, n3: n1 * n2 * n3 # Main program. # Calling anonymous function with passing arguments and stored the returned result into a variable m. m = multiply(20, 30, 40) print("Multiplication of three numbers =",m)
Output: Multiplication of three numbers = 24000
Use of Lambda Function in Python
There are the following some significant uses of lambda function in Python programming language. They are:
- When we need to define a function with no any name for a brief span of time, use lambda or anonymous function.
- In Python, we can use lambda functions as arguments for other functions.
- We can use lambda function with built-in functions such as map() and filter().
- We can use the lambda function when we want to use some anonymous function inside another function. For example:
Example 4:
Let’s write a program to calculate xn value by passing lambda function to a high order function.
def my_func(n): return lambda x: x ** n result = my_func(3) print(result(2))
Output: 8
Sorting with Lambda function
In Python, we generally use lambda function as an argument to a higher order function. It is a function that accepts other functions as arguments or returns them.
For example, we can pass lambda function to sorted() function to sort a dictionary by values. Look at the below program code to understand better.
Example 5:
# Creating a dictionary. dic = {25:'John', 15:'Bob', 5:'Magda', 10:'Anne'} # Lambda function takes all elements of dictionary and returns a value. sorted_dic = sorted(dic.items(), key= lambda kv : kv[1]) print(sorted_dic)
Output: [(10, 'Anne'), (15, 'Bob'), (25, 'John'), (5, 'Magda')]
In this example, we have used sorted() function that take a parameter key. It refers to lambda function that extracts a comparison for each element in the first argument of sorted() function. The default value of key is None that denotes elements in the first argument are to be compared directly.
To facilitate function programming, Python provides three built-in higher order functions: map(), filter(), and reduce(). We can use lambda function along with map(), filter(), and reduce() to simplify implementation of functions that operate over sequences like strings, lists, tuples, etc.
Let’s understand each one with the help of examples.
Use of Lambda function with map()
Python’s map() function takes inside a function and a list as arguments. The function is called with lambda function and all elements in the list.
This function returns a new list containing all lambda modified elements returned by that function for each element in the original list.
Let’s take an example in which we will see how do we use the map() function with the lambda function to get the squared value of every integer in the list.
Example 6:
# Creating a list of numbers. num_list = [2, 4, 6, 8, 10, 12, 8] # Usage of lambda function. squared_list = list(map(lambda x: x ** 2 , num_list)) print(squared_list)
Output: [4, 16, 36, 64, 100, 144, 64]
Example 7:
num_list = [2, 4, 6, 8, 10, 12, 8] print('Original list:',num_list) # Usage of lambda function that increments elements in the list by 2. new_list = list(map(lambda x: x + 2 , num_list)) print('New list after increment:',new_list)
Output: Original list: [2, 4, 6, 8, 10, 12, 8] New list after increment: [4, 6, 8, 10, 12, 14, 10]
Use of Lambda function with filter()
Python’s filter() function takes in a function and a list as parameters. Then, the function is called with lambda function and all elements in the list. This function returns a new list that contains elements returned from each element in the original list that evaluates to True.
Here is a simple example of the usage of the filter() function in a program that returns a list of even numbers after filtering out odd numbers from a specified list.
Example 8:
num_list = [2, 4, 9, 7, 10, 12, 13, 16] print('Original list:',num_list) # Usage of lambda function that filters out only even numbers from a specified list. new_list = list(filter(lambda x: x % 2 == 0 , num_list)) print('New list after filtering out even numbers:',new_list)
Output: Original list: [2, 4, 9, 7, 10, 12, 13, 16] New list after filtering out even numbers: [2, 4, 10, 12, 16]
Usage of Lambda function with reduce()
Python’s reduce() function takes in a function and a list as parameters. The function is invoked with a lambda function and a list that returns a newly reduced result. It performs a repetitive operation over the pairs of the list.
Below is a simple example in which we have used the lambda function with reduce(), computing the product of a list of integers.
Example 9:
import functools num_list = [1, 2, 3, 4, 5, 6] product = functools.reduce(lambda x, y: x * y, num_list) print('Product of numbers:',product)
Output: Product of numbers: 720
In this tutorial, you have learned about anonymous or lambda function in Python with the help of some useful examples. Hope that you will have understood the basic concept of lambda function and practiced all example programs.
Thanks for reading!!!