[Python-Dev] Behaviour of max() and min() with equal keys

Mark Dickinson dickinsm at gmail.com
Tue Sep 7 22:44:03 CEST 2010

On Tue, Sep 7, 2010 at 8:34 PM, Matthew Woodcraft
<matthew at woodcraft.me.uk> wrote:
> In CPython, the builtin max() and min() have the property that if there
> are items with equal keys, the first item is returned. From a quick look
> at their source, I think this is true for Jython and IronPython too.

It's actually not clear to me that this behaviour is ideal;  it might
make more sense to have max() return the first item among equal
largest elements, and min() return the last item.  That way, the
special case of two operands has the nice property that (max(x, y),
min(x, y)) is always either (x, y) or (y, x), rather than being
possibly (x, x) or (y, y).  (That is, id(max(x, y)) and id(min(x, y))
are id(x) and id(y) in one order or the other.)

The max and min methods for the Decimal module take care to work this
way, for example:

>>> x, y = Decimal(2), Decimal('2.0')
>>> x.max(y), x.min(y)
(Decimal('2'), Decimal('2.0'))


>>> max(x, y), min(x, y)
(Decimal('2'), Decimal('2'))

Can you give examples of code that relies on max and min returning the
first among equals?


More information about the Python-Dev mailing list