[Python-ideas] Have max and min functions ignore None

Steven D'Aprano steve at pearwood.info
Tue Dec 29 06:22:58 EST 2015


On Mon, Dec 28, 2015 at 11:08:49PM -0500, Franklin? Lee wrote:

> What do people think about having `max` and `min` ignore `None`?

I'd want to think about it carefully. I think that there might be a good 
case for making max and min a bit more sophisticated, but I'm not quite 
sure how sophisticated. There's more to it than just None.

If you think of None as just some value, then including None in a list 
of numbers (say) is an error, and should raise an exception as it does 
now (in Python 3, not Python 2). So that's perfectly reasonable, and 
correct, behaviour.

If you think of None as representing a missing value, then there are two 
equally good interpretations of max(x, None): either we ignore missing 
values and return x, or we say that if one value is unknown, the max is 
also clearly unknown, and propagate that missing value as the answer.

So that's three perfectly reasonable behaviours:

max(x, None) is an error and should raise;
max(x, None) ignores None and returns x;
max(x, None) is unknown or missing and returns None
(or some other sentinel representing NA/Missing/Unknown).


In R, the max or min of a list with missing values is the 
missing value, unless you specifically tell R to ignore NA:

  > max(c(1, 2, 3, NA))
  [1] NA
  > max(c(1, 2, 3, NA), na.rm=TRUE)
  [1] 3

In Javascript, I guess the equivalent would be null, which appears to 
be coerced to 0:

  js> Math.max(1, 2, null, 4)
  4
  js> Math.min(1, 2, null, 4)
  0

I don't think there is any good justification for that behaviour. 
That's the sort of thing which gives weakly typed languages a bad 
name.

Just tossing this out to be shot down...

What if the builtin max and min remained unchanged, but we added 
variants of them to the statistics module which treated None as a 
missing value, to be either ignored or propagated, as R does?


-- 
Steve


More information about the Python-ideas mailing list