[Python-ideas] Make max() stable
Steven D'Aprano
steve at pearwood.info
Sat Jan 18 09:12:48 CET 2014
On Fri, Jan 17, 2014 at 11:40:49PM -0800, Devin Jeanpierre wrote:
> On Fri, Jan 17, 2014 at 5:35 PM, Ned Batchelder <ned at nedbatchelder.com> wrote:
> > Is there an example of an actual problem that stability of min and max would
> > make easier to solve?
>
> In a language like C++, you if min and max had the property specified
> by the OP, you might do:
>
> x = min(a, b);
> y = max(a, b);
>
> And then x is the smallest, and y is the other one, and it's simple and
> easy and less code than an if statement.
But that's how max and min work right now, modulo that object identity
is not important. If you care about object identity, you're probably
doing something underhanded *wink*
Given the case that a and b are *equal* (as measured by the key
function, if given) then it shouldn't matter whether you get
smallest = a
biggest = b
or
smallest = b
biggest = a
or
smallest = biggest = a
or
smallest = biggest = b
These variations only are meaningful if a and b are different types
with the same value, or the same type but different identities. Even if
these variations are important, I don't think there is any inherent
benefit to one over the other.
Personally, I'd either keep the current behaviour, or purely for the
symmetry, pick the so-called "stable" behaviour. But I don't see any
rational reason for preferring one over the other. Now that Python 3
documents the specific behaviour, it's not worth changing.
> I suspect this is where the desire comes from.
>
> In Python, of course, you do x, y = sorted([a, b])
Now the interesting thing here is that sorted *is* stable, so if a and b
are equal, sorted([a, b]) is guaranteed to return [a, b]. Which gives
the behaviour requested.
--
Steven
More information about the Python-ideas
mailing list