Examples for map, filter, and reduce in Python


In [25]:
items = range(1, 6)
squared =[]
for x in items:
    squared.append(x**2)

def sqr(x):
    return x **2

list(map(sqr, items))
list(map((lambda p: p**2), items))

def square(x):
    return (x**2)
def cube(x):
    return (x**3)
funcs=[square, cube]
for r in range(5):
    value=map(lambda x: x(r), funcs)
    print value

def mymap(aFunc, aSeq):
    result=[]
    for x in aSeq:
        result.append(aFunc(x))
    return result
list(map(sqr, [1,2,3]))
mymap(sqr, [1,2,3])

map((lambda i : (i, 1) ), [1,2,3])
list(range(-5, 5))

list(filter((lambda x: x<0), range(-5,5)))

from functools import reduce
reduce((lambda x,y:x+y), [1,2,3,4])


[0, 0]
[1, 1]
[4, 8]
[9, 27]
[16, 64]
Out[25]:
10