List minimum in Python with None?

Question:

Is there any clever in-built function or something that will return 1 for the min() example below? (I bet there is a solid reason for it not to return anything, but in my particular case I need it to disregard None values really bad!)

>>> max([None, 1,2])
2
>>> min([None, 1,2])
>>> 
Asked By: c00kiemonster

||

Answers:

None is being returned

>>> print min([None, 1,2])
None
>>> None < 1
True

If you want to return 1 you have to filter the None away:

>>> L = [None, 1, 2]
>>> min(x for x in L if x is not None)
1
Answered By: nosklo

using a generator expression:

>>> min(value for value in [None,1,2] if value is not None)
1

eventually, you may use filter:

>>> min(filter(lambda x: x is not None, [None,1,2]))
1
Answered By: Adrien Plisson

Make None infinite for min():

def noneIsInfinite(value):
    if value is None:
        return float("inf")
    else:
        return value

>>> print min([1,2,None], key=noneIsInfinite)
1

Note: this approach works for python 3 as well.

Answered By: gregory
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.