Python: Difference between filter(function, sequence) and map(function, sequence)
list(map(cube, range(1, 11)))
is equivalent to
[cube(1), cube(2), ..., cube(10)]
While the list returned by
list(filter(f, range(2, 25)))
is equivalent to result
after running
result = []
for i in range(2, 25):
if f(i):
result.append(i)
Notice that when using map
, the items in the result are values returned by the function cube
.
In contrast, the values returned by f
in filter(f, ...)
are not the items in result
. f(i)
is only used to determine if the value i
should be kept in result
.
In Python2, map
and filter
return lists. In Python3, map
and filter
return iterators. Above, list(map(...))
and list(filter(...))
is used to ensure the result is a list.
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]
map
and filter
function in python is pretty different because they perform very differently. Let's have a quick example to differentiate them.
map function
Let's define a function which will take a string argument and check whether it presents in vowel letter sequences.
def lit(word):
return word in 'aeiou'
Now let's create a map function for this and pass some random string.
for item in map(lit,['a','b','e']):
print(item)
And yes it's equivalent to following
lit('a') , lit('b') , lit('e')
simply it will print
True
False
True
filter function
Now let's create a filter
function for this and pass some random string.
for item in filter(lit,['a','b','e']):
print(item)
filter
as the name implies, filters the original iterable and retents the items that return True for the function provided to the filter function.
Simply it will print
a
e
Fork it here for future reference, if you find this useful.