Search code examples
pythonfilterfunctional-programmingmap-function

Is it possible to implement filter function using only map?


I was wondering whether it is possible to implement filter function using only map function in Python. Suppose I have a list A = [1,2,3,4,5,6,7,8,9,10] and I want to get only even numbers. Applying filter function provides me a list of 5 elements but map always returns 10 elements no matter what functions I could think.

Is there any way to achieve this?

Please don't suggest to apply filter again on the result of map. :-)


Solution

  • No. map will only apply a function to all the elements of the list. Thus, the number of elements in the resulting list (or generator) will always be the same as in the original list.

    (Technically, you could use map with a function that uses side-effects to add the even elements to some other list and use that list as the result, but this is not how map is supposed to be used.)