Exclude null values in map function of Python3

Question:

I am using map to process a list in Python3.6:

def calc(num):
    if num > 5:
        return None
    return num * 2


r = map(lambda num: clac(num), range(1, 10))
print(list(r))

# => [2, 4, 6, 8, 10, None, None, None, None]

The result I expect is: [2, 4, 6, 8, 10].

Of course, I can use filter to handle map result. But is there a way for map to return directly to the result I want?

Asked By: Martin Zhu

||

Answers:

Not when using map itself, but you can change your map() call to:

r = [calc(num) for num in range(1, 10) if calc(num) is not None]
print(r)  # no need to wrap in list() anymore

to get the result you want.

Answered By: viraptor

map cannot directly filter out items. It outputs one item for each item of input. You can use a list comprehension to filter out None from your results.

r = [x for x in map(calc, range(1,10)) if x is not None]

(This only calls calc once on each number in the range.)

Aside: there is no need to write lambda num: calc(num). If you want a function that returns the result of calc, just use calc itself.

Answered By: khelwood
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.