List minimum in Python with None?

c00kiemonster picture c00kiemonster · Feb 19, 2010 · Viewed 22.1k times · Source

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

Answer

nosklo picture nosklo · Feb 19, 2010

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