The reason of None
is because the function map
performs its functions for each element in the list, so that a return on these functions is always necessary. As you do not return anything in the else
(that does not exist in its functions), Python assumes None
in such cases.
If you are required to use the map
, a possible solution is to simply remove the None
after the call from map
, maybe using a understanding:
lista = [0,1,2,3,4,5,6,7,8,9,10]
def par(numero):
if numero % 2 == 0:
return numero
def impar(numero):
if numero % 2 != 0:
return numero
par = [i for i in list(map(par,lista)) if i is not None]
impar = [i for i in list(map(impar,lista)) if i is not None]
print(par)
print(impar)
Note that while doing par = ...
you change your function par
previously defined so that it can no longer be used.
Maybe it would be good to use another variable name. :)
If on the other hand you don’t need to use the map
, does directly:
lista = [0,1,2,3,4,5,6,7,8,9,10]
par = [i for i in lista if i % 2 == 0]
impar = [i for i in lista if i % 2 != 0]
print(par)
print(impar)
There is still another option. If you are using Numpy, you can do so:
import numpy as np
lista = np.array([0,1,2,3,4,5,6,7,8,9,10])
paridx = np.logical_not((lista % 2).astype(bool))
imparidx = (lista % 2).astype(bool)
par = lista[paridx]
impar = lista[imparidx]
print(par)
print(impar)
Explaining:
- The command
lista % 2
returns a list with the leftover division of each element by 2, which for your list it will return [0 1 0 1 0 1 0 1 0 1 0]
.
- The command
(lista % 2).astype(bool)
simply converts these 0s and 1s to logical values, making this list become [False True False True False True False True False True False]
. Note how basically it indicates False
where the rest of the split by 2 is zero, and True
where the rest of the division by 2 is 1. That is, basically it indicates true where the number at that position (index) is odd.
- That’s why the final command is
(lista % 2).astype(bool)
to indicate the odd number indices and np.logical_not((lista % 2).astype(bool))
(the logical negation of these values) to indicate the indices of even numbers.
- Finally, these indexes are used directly to "filter" in the original list the items where the index indicates true (
True
) - a very nice and useful resource when manipulating data: par = lista[paridx]
and impar = lista[imparidx]
.