I\'m reading through the Python documentation to really get in depth with the Python language and came across the filter and map functions. I have used filter before, but never
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.