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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)