Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List minimum in Python with None?

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]) >>>  
like image 502
c00kiemonster Avatar asked Feb 19 '10 10:02

c00kiemonster


People also ask

Can I put none in a list Python?

None is a valid element, but you can treat it like a stub or placeholder. So it counts as an element inside the list even if there is only a None .

How do you find the minimum of a list in Python?

The Python min() function returns the lowest value in a list of items. min() can be used to find the smallest number in a list or first string that would appear in the list if the list were ordered alphabetically.

How do you find the minimum value of multiple lists in Python?

Using min() and zip() In the below example we use the min() and zip(). Here the zip() function organizes the elements at the same index from multiple lists into a single list. Then we apply the min() function to the result of zip function using a for loop.


1 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 
like image 147
nosklo Avatar answered Sep 20 '22 03:09

nosklo