Python Filter/Maps

filter(), as its name suggests, filters the original iterable and retents the items that returns True for the function provided to filter().

map() on the other hand, apply the supplied function to each element of the iterable and return a list of results for each element.


Follows the example that you gave, let's compare them:
>>> def f(x): return x % 2 != 0 and x % 3 != 0
>>> range(11)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> map(f, range(11)) #the ones that returns TRUE are 1, 5 and 7
[False, True, False, False, False, True, False, True, False, False, False]
>>> filter(f, range(11)) #So, filter returns 1, 5 and 7
[1, 5, 7]

No comments:

Post a Comment