Getting max value from a list with None elements

10,710

Solution 1

First, convert to a numpy array. Specify dtype=np.floatX, and all those Nones will be casted to np.nan type.

import numpy as np

lst = [1, 2, 3, 4, 5, None]

x = np.array(lst, dtype=np.float64)
print(x)
array([  1.,   2.,   3.,   4.,   5.,  nan])

Now, call np.nanmax:

print(np.nanmax(x))
5.0

To return the max as an integer, you can use .astype:

print(np.nanmax(x).astype(int)) # or int(np.nanmax(x))
5

This approach works as of v1.13.1.

Solution 2

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 Nones 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)

Solution 3

In Python 2

max([i for i in LIST if i is not None])

Simple in Python 3 onwards

max(filter(None.__ne__, LIST))

Or more verbosely

max(filter(lambda v: v is not None, LIST))

Solution 4

You can use a simple list-comprehension to first filter out Nones:

np.nanmax([x for x in LIST if x is not None])

Solution 5

Here is what I would do:

>>> max(el for el in LIST if el is not None)
5

It is superficially similar to the other answers, but is subtly different in that it uses a generator expression rather than a list comprehension. The difference is that it doesn't create an intermediate list to store the result of the filtering.

Share:
10,710
Chris T.
Author by

Chris T.

Updated on June 04, 2022

Comments

  • Chris T.
    Chris T. almost 2 years

    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?