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

Question:

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}

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?

Asked By: Cris

||

Answers:

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}; for tuples, you need a trailing comma: (*generator,). (Thanks, @MustafaAydin.)

Answered By: rici