I'm trying to get maximal value from a list object that contains nonetype using the following code:
import numpy as np
LIST = [1,2,3,4,5,None]
np.nanmax(LIST)
But I received this error message
'>=' not supported between instances of 'int' and 'NoneType'
Clearly np.nanmax()
doesn't work with None
. What's the alternative way to get max value from list objects that contain None
values?
One approach could be -
max([i for i in LIST if i is not None])
Sample runs -
In [184]: LIST = [1,2,3,4,5,None]
In [185]: max([i for i in LIST if i is not None])
Out[185]: 5
In [186]: LIST = [1,2,3,4,5,None, 6, 9]
In [187]: max([i for i in LIST if i is not None])
Out[187]: 9
Based on comments from OP
, it seems we could have an input list of all None
s and for that special case, it output should be [None, None, None]
. For the otherwise case, the output would be the scalar max
value. So, to solve for such a scenario, we could do -
a = [i for i in LIST if i is not None]
out = [None]*3 if len(a)==0 else max(a)