Python Tutorial

Thursday, January 16, 2014

python filter(), map(), reduce() with list

  • filter(function, sequence) : returns sequence for which function(item) is true
  • map(function, sequence): call function(item) for each item and returns a list
  • reduce(function, sequence): returns a single value constructed by calling function on first two items on the sequence, then the result and the next item, and so on.
def f(x):
    return x % 2 == 0
print filter(f, range(1,10))

def square(x):
    return x*x
print map(square, range(1,5))

def add(x, y):
    return x+y
print reduce(add, range(1,10))

[2, 4, 6, 8]
[1, 4, 9, 16]


Post a Comment