Search code examples
pythonlambdafunctional-programmingmap-function

Map and comparison in python


Say I have a list:

foo_list = ["foo", None, "bar", 1, 0, None]

I want to transform this list into a boolean list saying which elements are None, like

results = [False, True, False, False, False, True]

A simple map and lambda will do:

list(map(lambda a: a==None, foo_list))

but I want to know if I can remove the lambda, and make it even simpler, something along the lines of:

list(map((==None), foo_list))

which obviously throws an error, but other functional languages often allow operators as functions, and technically this function isn't even curried (since it has all the arguments it needs).

Edit: I am aware of list comprehensions in Python, and that this could be solved as [(a==None) for a in foo_list], but that is not my question.


Solution

  • I’d say the list comprehension is the Pythonic way, but if you really want to, you could do

    import functools
    import operator
    foo_list = ["foo", None, "bar", 1, 0, None]
    print(list(map(functools.partial(operator.is_, None), foo_list)))