Python Anonymous/lambda
Function#
Learn about the anonymous function, also known as lambda
functions. You’ll learn what they are, their syntax and how to use them (with examples).
What are lambda
functions in Python?#
In Python, an anonymous function is a function that is defined without a name.
While normal functions are defined using the def
keyword in Python, anonymous functions are defined using the lambda
keyword.
APython lambda
function is a single expression. But, in a lambda body, we can expand with expressions over multiple lines using parentheses ()
or a multiline string """ """
.
For example: lambda n:n+n
The reason behind the using anonymous function is for instant use, that is, one-time usage and the code is very concise so that there is more readability in the code.
Hence, anonymous functions are also called lambda
functions.
Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions.
An anonymous function cannot be a direct call to print because lambda requires an expression.
lambda
functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace.Although it appears that lambdas are a one-line version of a function, they are not equivalent to inline statements in C or C++, whose purpose is to stack allocation by passing function, during invocation for performance reasons.
Syntax:
lambda argument_list: expression
Let’s see an example to print even numbers without a lambda
function and with a lambda
function. See the difference in line of code as well as readability of code.
# Example 1: Program for even numbers without lambda function
def even_numbers(nums):
even_list = []
for n in nums:
if n % 2 == 0:
even_list.append(n)
return even_list
num_list = [10, 9, 16, 78, 2, 3, 7, 1]
ans = even_numbers(num_list)
print("Even numbers are:", ans)
Even numbers are: [10, 16, 78, 2]
# Example 1: Program for even number with a lambda function
l = [10, 9, 16, 78, 2, 3, 7, 1]
even_nos = list(filter(lambda x: x % 2 == 0, l))
print("Even numbers are: ", even_nos)
Even numbers are: [10, 16, 78, 2]
# Example 2: Program to show the use of lambda functions
double = lambda x: x * 2
print(double(6))
12
Explanation:
In the above program, lambda x: x * 2
is the lambda function. Here x
is the argument and x * 2
is the expression that gets evaluated and returned.
This function has no name. It returns a function object which is assigned to the identifier double
. We can now call it as a normal function. The statement
>>> double = lambda x: x * 2
is nearly the same as:
>>> def double(x):
>>> return x * 2
# Example 3: Normal Function definition is here
def square(x):
return x*x
# anonymous function
sqr = lambda x: x*x
#Calling square function
print("Square of number is",square(10)) #call normal function
print("Square of number is",sqr(2)) #call anonymous function
Square of number is 100
Square of number is 4
Use of lambda
Function in python#
We use lambda
function when we require a nameless function for a short period of time.
In Python, we generally use it as an argument to a higher-order function (a function that takes in other functions as arguments). lambda
function are used along with built-in functions like filter()
, map()
, reduce()
etc.
lambda
function use with filter()
#
The filter()
function in Python takes in a function and a list as arguments.
The function is called with all the items in the list and a new list is returned which contains items for which the function evaluates to True
.
Here is an example use of filter()
function to filter out only even numbers from a list.
# Example 1: Program to filter out only the even items from a list
my_list = [1, 5, 4, 6, 8, 11, 3, 12] # total 8 elements
new_list = list(filter(lambda x: (x%2 == 0), my_list)) # returns the output in form of a list
print("Even numbers are: ", new_list)
Even numbers are: [4, 6, 8, 12]
# Example 2:
l = [-10, 5, 12, -78, 6, -1, -7, 9]
positive_nos = list(filter(lambda x: x > 0, l))
print("Positive numbers are: ", positive_nos)
Positive numbers are: [5, 12, 6, 9]
lambda
function with map()
#
The map()
function in Python takes in a function and a list.
The function is called with all the items in the list and a new list is returned which contains items returned by that function for each item.
Here is an example use of map()
function to double all the items in a list.
# Example 1: Program to double each item in a list using map()
my_list = [1, 5, 4, 6, 8, 11, 3, 12] # total 8 elements
new_list = list(map(lambda x: x * 2, my_list)) # returns the output in form of a list
print("Double values are: ", new_list)
Double values are: [2, 10, 8, 12, 16, 22, 6, 24]
# Example 2:
list1 = [2, 3, 4, 8, 9]
list2 = list(map(lambda x: x*x*x, list1))
print("Cube values are:", list2)
Cube values are: [8, 27, 64, 512, 729]
lambda
function with reduce()
#
The reduce()
function is used to minimize sequence elements into a single value by applying the specified condition.
The reduce()
function is present in the functools
module; hence, we need to import it using the import statement before using it.
# Example 1:
from functools import reduce
list1 = [20, 13, 4, 8, 9]
add = reduce(lambda x, y: x+y, list1)
print("Addition of all list elements is : ", add)
Addition of all list elements is : 54