Brought to you by molecularsciences.org.
This work is licensed under a Creative Commons Attribution-Share Alike 3.0 License.
This publication may not be redistributed without this notice.

Applying functions on a lists using filter, map, reduce

filter(function,sequence)
Applies a function to every element in the sequence. Returns only when the item returns true.

def even_numbers(x):
	return x % 2 == 0

print "Even Numbers"
print filter(even_numbers, range(10,20))

output

Even Numbers
[10, 12, 14, 16, 18]

map(function, sequence)
Applies a function to every element in the sequence and returns the results of the function for each element.

def circumference(r):
	a = 2 * 3.14 * r
	return int(a)

print "Gives Circumference"
print map(circumference, range(10,20))

output

Gives Circumference
[62, 69, 75, 81, 87, 94, 100, 106, 113, 119]

reduce(function, sequence)
returns a single value created sliding window operation on a list

def adder(a,b):
	return a + b

expenses = (546,675,897,57,4,87,454)
# total expenses
print reduce(adder, expenses)

output

2720