min() & max() vs sorted()

MRAB google at mrabarnett.plus.com
Sat Sep 16 00:51:30 CEST 2006

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

More information about the Python-list mailing list