Monday 30 December 2019

Using Lambda with filter () ,map() and reduce() function


Using lambdas with filter()
#without using lambda function with filter()
def even(n):
    if n%2==0:
        return True
    else:
        return False
a=[0,5,10,20,25,30]#created list
#b=list(filter(even,a))
b=list((even,a))
print(b)
"""output:
[0, 10, 20, 30]

filter() is used to filter the data from the given sequence based on some condition

Syntax: filter(function,sequence)

# Same program with using lambda function with filter()
"""def even(n):
    if n%2==0:
        return True
    else:
        return False"""

a=[0,5,10,20,25,30]#created list
b=list(filter(lambda n:n%2==0,a))
print(b)
#odd nos
b=list(filter(lambda n:n%2!=0,a))
print(b)
"""output:
[0, 10, 20, 30]
[5, 25]
"""
It is normally used with Lambda functions to separate list, tuple, or sets.
map() function

It is similar to filter() but it acts on each element of the sequence and generate new sequence.

Without lambda function:
a=[1,2,3,4,5]#list created
def double(n):
    return 2*n
b=list(map(double,a))
print(b)
"""output:
[2, 4, 6, 8, 10]
"""
#without lambda function
a=[1,2,3,4,5]#list created
"""def double(n):
    return 2*n
b=list(map(square,a))"""
b=list(map(lambda n:2*n,a))
print(b)
"""output:
[2, 4, 6, 8, 10]
"""
reduce() function

from functools import*
a=[10,20,30,40,50]
b=reduce(lambda x,y:x+y,a)
print(b)

"""
output:150
1q) if we don't write import:
Ans:NameError: name 'reduce' is not defined
Or we can write
from functools import*

"""
Reduce() function reduces sequence of elements into a single value by processing the elements according to the functionality.

Syntax: reduce(function,sequence)

Example:
from functools import*
a=[1,2,3,4,5]
b=reduce(lambda x,y:x*y,a)
print(b)
or
import functools
a=[1,2,3,4,5]
b=functools.reduce(lambda x,y:x*y,a)
print(b)
"""

output:120

Related video links:
https://youtu.be/tlexI5d6LI0
https://youtu.be/WgSk2cGcraQ


Next: Decorator function
Prev:Lambda function

No comments:

Post a Comment

Files with Exception handling

#Ask the user to take two input integer values var a,b try:     a=int(input("enter any integer value:"))     b=int(input(&qu...