Introducing Python © Chirag Wazir 2002 Prev   Index   Next

Functional Programming Constructs

f = lambda x: x ** 2
f(5)
      25
filter(lambda x: x % 2 == 0, range(0, 10))
      [0, 2, 4, 6, 8]
map(lambda x: x**3, range(1,10))
      [1, 8, 27, 64, 125, 216, 343, 512, 729]
map(None, range(1, 5), "abcd")
      [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]
reduce(lambda x, y: x+y, [15, 12, 37, 5, 11])
      80

filter(function, sequence) returns a sequence (of the same type, if possible) consisting of those items from the sequence for which function(item) is true.

map(function, sequence) calls function(item) for each of the sequence's items and returns a list of the return values.

reduce(func, sequence) returns a single value constructed by calling the binary function func on the first two items of the sequence, then on the result and the next item, and so on.

List Comprehensions

vec = [2, 4, 6]
[3*x for x in vec]
      [6, 12, 18]
[3*x for x in vec if x > 3]
      [12, 18]
[(x, x**2) for x in vec]
      [(2, 4), (4, 16), (6, 36)]
vec1 = [2, 4, 6]
vec2 = [4, 3, -9]
[(x, y) for x in vec1 for y in vec2]
      [(2, 4), (2, 3), (2, -9), (4, 4), (4, 3), (4, -9), (6, 4), (6, 3), (6, -9)]
[x+y for x in vec1 for y in vec2]
      [6, 5, -7, 8, 7, -5, 10, 9, -3]
[vec1[i]*vec2[i] for i in range(len(vec1))]
      [8, 12, -54]