Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Where did the "None"s come from? | Python map() function

I wrote a little code that uses the map() function:

def function(a):
if a % 2 == 0:
    return a
else: 
    pass
x = map(function, (1,3,2,5,6))
print(set(x))

It’s supposed to return every even number that is provided, If it’s an odd number, I don’t want it to return anything, so I put "pass". However, when I run it, the output goes like this:

{2, 6, None}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is weird, I’m not sure where the "None" came from, and when I change the set() function that is used to print the X to either list() or tuple(), the output goes like these:

[None, None, 2, None, 6] or (None, None, 2, None, 6)

I’m not really sure what’s going on here, the odd numbers weren’t supposed to return anything but instead, it’s still there as "None". Is there a way I could fix this? What caused this in the first place?

>Solution :

Every Python function returns something. If no return statement is executed, or the return statement has no expression, then the function returns None. And that’s where your Nones come from.

If you want to filter a list of values by some criterion, write a function which returns True or False (or equivalents), and use the filter built-in:

>>> def isEven(a):
...     return a % 2 == 0

>>> [*filter(isEven, (1,3,2,5,6))]
[2, 6]

[*generator] turns a generator into a list. That also works with sets, using {*generator}, but not with tuples.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading