Python Lambda Functions

What are lambda functions in Python?

Lambda functions, also known as anonymous function are the functions without a name. As Python uses the def keyword to define the function, but to define a lambda function, we do not need to use the keyword def. A lambda function can take any number of arguments, but can only have one expression.

Loading...

How to use lambda Functions in Python?

The syntax of the lambda function is:-
lambda arguments: expression

Example of Lambda Function in python

Let us be more clear with an example that shows the use of lambda function over normal function.

def square(y):
    return y * y


sq = lambda x: x * x

print("Normal Function square(): ", square(5))
print("Lambda Function sq():", sq(7))

The output of the above program is:-

Normal Function square(): 25
Lambda Function sq(): 49
In the above program, we can see that one way of defining a function is to use def keyword and lambda function makes it easier to write such function in a single line of code. Here,  x is the argument and x * x is the expression. We can use multiple arguments in lambda function, but the expression should be only one.
Lambda functions can be used along with built-in functions like filter(), map() and reduce().

Use of Lambda Function with map()

map() function takes two arguments, viz. a function and a list. The function is called with a lambda function and a list and a new list is returned which contains all the lambda modified items returned by that function for each item.

For Example:

mylist = [2, 5, 19, 25, 34, 55]
updated_list = list(map(lambda x: x * 2, mylist))
print(updated_list)

The output is:-

[4, 10, 38, 50, 68, 110]

Use of Lambda Function with filter()

The filter() function takes a function and a list as arguments. This offers an elegant way to filter out all the elements of a sequence “sequence”, for which the function returns True. Here is an example program that returns the even numbers from an input list:

mylist = [3, 10, 17, 23, 124, 450, 300, 301, 304]
updatded_list = list(filter(lambda x: (x % 2 == 0), mylist))
print(updatded_list)

The output of the program is:-

[10, 124, 450, 300, 304]

Use of Lambda Function with reduce()

The reduce() function takes a function and a list as arguments. The function is called with a lambda function and a list and a new reduced result is returned. This performs a repetitive operation over the pairs of the list. This is a part of the functools module.

from functools import reduce
mylist = [3, 10, 17, 23, 124, 450, 300, 301, 304]
sum = reduce((lambda x, y: x + y), mylist)
print("Sum = ", sum)

The output of the program is:-

Sum = 1532
Loading...
SHARE Python Lambda Functions

You may also like...

Leave a Reply

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

Share