min() & max() vs sorted()

Tim Peters tim.peters at gmail.com
Thu Sep 14 20:56:31 EDT 2006


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

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

> I think that's just down to a subtlety in the way that 'max' is written.

It's straightforward, skipping error cases:

def max(*args):
     is_first_arg = True
     for arg in args:
         if is_first_arg:
             winner = arg
             is_first_arg = False
        elif arg > winner:    # only difference in min() is "<" here instead
             winner = arg
    return winner



More information about the Python-list mailing list