# min() & max() vs sorted()

Sat Sep 16 08:28:53 CEST 2006

```MRAB wrote:
> Tim Peters wrote:
> > [MRAB]
> > > Some time after reading about Python 2.5 and how the built-in functions
> > > 'min' and 'max' will be getting a new 'key' argument, I wondered how
> > > they would treat those cases where the keys were the same, for example:
> > >
> > > L = ["four", "five"]
> > > print min(L, key = len), max(L, key = len)
> > >
> > > The result is:
> > >
> > > ('four', 'four')
> >
> > min() and max() both work left-to-right, and return the minimal or
> > maximal element at the smallest index.
> >
> It doesn't say that in the documentation.
>
> > > I would've thought that min(...) should return the same as
> > > sorted(...)[0] (which it does)
> >
> > It does, but only because Python's sort is stable, so that minimal
> > elements retain their original relative order.  That implies that the
> > minimal element with smallest original index will end up at index 0
> > after sorting.
> >
> > > and that max(...) should return the same as sorted(...)[-1] (which it doesn't).
> >
> > Right -- although I don't know why you'd expect that.
> >
> Strings have index(), find(), etc which work left-to-right and
> rindex(), rfind(), etc which work right-to-left.
>
> Lists have index() but not rindex().
>
> I just thought that if min() and max() work left-to-right then for
> completeness there should also be rmin() and rmax(); alternatively,
> min() should return sorted()[0] and max() should return sorted()[-1]
> for symmetry (my personal preference).

Strange, but I've never thought of min and max in the way you do. If
anything I think of them as being distinct from sort; a way to get the
appropriate values without going to the bother of a full sort. After
cPythons sort algorithm, if I want just max or min, then I won't go
sorting in a hurry. I am quite happy with min and max just returning
the value.
With the addition of the key then I might want the option of returning