1

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. :-)

Georgy
  • 12,464
  • 7
  • 65
  • 73
Kishan Pandey
  • 191
  • 1
  • 8
  • 1
    what is the bigger picture here? `map()` is for applying a function to each item of an iterable not for filtering data. As you seem to already know you can use `filter()` for that or a comprehension like `[item for item in data if predicate]` – Chris_Rands Nov 27 '19 at 10:03
  • Beaten to it, but `B = [x for x in A if not x%2]` for example, would be a simple solution for your example problem. – David Buck Nov 27 '19 at 10:04
  • @DavidBuck I . That is essentially a filter function using list comprehension. I just wanted to know whether map is sufficient to implement all the functions. – Kishan Pandey Nov 27 '19 at 10:06
  • Related: [Exclude null values in map function of Python3](https://stackoverflow.com/q/51189698/7851470) – Georgy Nov 27 '19 at 10:23
  • No, but you can implement map, filter, etc. in terms of reduce. – Jared Smith Nov 27 '19 at 14:38

1 Answers1

4

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.)

tobias_k
  • 81,265
  • 12
  • 120
  • 179
  • 1
    (e.g. `even = []; list(map(lambda x: x % 2 == 0 and even.append(x), A)); print(even)`) – Chris_Rands Nov 27 '19 at 10:08
  • 2
    @Chris_Rands Yeah, I really did _not_ want to show that, though... – tobias_k Nov 27 '19 at 10:09
  • One could also combine `map` with e.g. `reduce` to get a "filtered" list without using `filter`, but again, that's not how things should be done. – tobias_k Nov 27 '19 at 10:19
  • a 'pure' `map()` solution... `list(map(lambda x: x if not x % 2 else next(iter([])), sorted(A, key=lambda x: x % 2)))`-- recommended of course ;) (might not work on all python versions...) – Chris_Rands Nov 27 '19 at 10:41
  • 1
    @Chris_Rands Wow, using `StopIteration` to kill the `map`? Not sure whether to upvote that comment or flag as "abusive"! :-D – tobias_k Nov 27 '19 at 10:47