To display only even numbers using map function

5.5k views Asked by At

I am a beginner and I have to implement a code to display only even numbers from 23 to 97 using map function. I got stuck at

def evenfunc(num):
    if num%2 == 0:
        return num
print map(evenfunc, range(23,98))

The output is [None, 24, None, 26, None, 28, None, 30, None, 32, None, 34, None, 36,....97] So how to get rid of the none values?

2

There are 2 answers

0
Christian Dean On BEST ANSWER

Your problem is that you misunderstand what the function that's passed into map should do. The function passed into map should modify the existing input. map maps the result of the function to each element, creating a new iterable. Not attempt to filter it.

You need to use filter instead, which is made to specifically filter input based upon a condition:

filter(lambda x: x % 2 == 0, range(23, 98))

However, a list comprehension would be a better choice:

[x for x in range(23, 98) if x % 2 == 0]
4
Kshitij Mittal On

Try this:

def evenfunc(num):
    if num%2 == 0:
        return True
print filter(evenfunc, range(23,98))