Analytics Vidhya
Published in

Analytics Vidhya

Creating own Reduce and Filter Function In Python

Basic ideas about working of loops and functions

source:-stack overflow
# Method I 
from functools import reduce
def sum(a,b):
return a+b
list_1=[10,15,25,10,40)
reduce(sum,list_1)
[out]>> 100
# Method II
from functools import reduce
list_1=[10,15,25,10,40]
reduce(lambda a,b :a+b,list_1)
[out]>>100
def myreduce(add,list_1):
return a
def add(a,b):
return a+b
list_1=[10,15,25,40,10]
a=list_1[0]
for i in range(1,len(list_1)):
b=list_1[i]
a=add(a,b)
print(myreduce(add,list_1))
[out]>> 100
def is_even(a):
if a%2==0:
return True
list_1=[2,3,4,5,6,7,8,9,12345,5678,890,1234,567]
list(filter(is_even,list_1))
[out]>> [2, 4, 6, 8, 5678, 890, 1234]
def myfilter(is_even,list_2):
return is_even(a)
list_2=[2,3,4,5,6,7,8,9,10]
list_3=[]
def is_even(a):
for i in list_2:
if i%2==0:
list_3.append(i)
print(list_3)
myfilter(is_even,list_2)
[out]>> [2, 4, 6, 8, 10]

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store