Python Function-lambda |filter, map, reduce.

Python Function

Pyhon funcrtion has 4 types that is Lambda, filter, map, reduce function.

Lambda

  • A lambda function is a small anonymous function.
  • A lambda function can take any number of arguments, but can only have one expression.

Syntax

Lambda arguments: expression

The expression is executed and the result is returned:

Let’s look at this example and try to understand.

#Square of given no
f=lambda x : x*x
print(f(7))

#Largest of two no
f=lambda x,y: x if (x>y) else y
print("Largest no",f(5,7))

#Calculate the sum of two no
f=lambda a,b: a+b
print("add:",f(2,3))

#calculate the multiplication
f=lambda a,b: a*b
a=int(input("Enter value:"))
b=int(input("Enter value:"))
print("Mul:",f(a,b)

Output.

>>> 
========== RESTART: C:/Users/User/Desktop/python/practise/lambda.py ==========
49
Largest no 7
add: 5
Enter value:2
Enter value:3
Mul: 6
>>> 

Lambda using Filter

filter function expects two arguments, function object and an iterable. function object returns a boolean value. function object is called for each element of the iterable and filter returns only those element for which the function object returns true. filter function also returns a list of element .

Filter

  • Filter=Take only true value and Store.
  • The filter () function in Python takes in 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.
li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]
odd_list = list(filter(lambda x: (x%2 != 0) , li))
print(odd_list) 
even_list = list(filter(lambda x: (x%2 == 0) , li))
print(even_list)

Output:
[5, 7, 97, 77, 23, 73, 61] [22, 54, 62]

Map Function

  • Map maps element of the list to another value as per expression in the lambda
square_list = list(map(lambda x: x*x,li))
 print(square_list) 
cube_list = list(map(lambda x:x*x*x,li)) 
print(cube_list) 

 

Output:
[25, 49, 484, 9409, 2916, 3844, 5929, 529, 5329, 3721] [125, 343, 10648, 912673, 157464, 238328, 456533, 12167, 389017, 226981]

Reduce Function

  • Reduces a list to result
li = [5, 8, 10, 20, 50, 100] 
sum = reduce((lambda x, y: x + y), li)
print(sum) mult = reduce((lambda x,y:x*y),li) 
print(mult)

“output 193 40000000

Output :
193
40000000

About Ashishkumar Vishwakarma

I am Ashish- a Developer live in Mumbai.

View all posts by Ashishkumar Vishwakarma →

One Comment on “Python Function-lambda |filter, map, reduce.”

  1. Hello there, You have done a fantastic job. I’ll certainly digg it and for my part recommend to my friends. I’m sure they’ll be benefited from this site.|

Leave a Reply