Which maximum does Python pick in the case of a tie?
From empirical testing, it appears that max()
and min()
on a list will return the first in the list that matches the max()
/min()
in the event of a tie:
>>> test = [(1, "a"), (1, "b"), (2, "c"), (2, "d")]
>>> max(test, key=lambda x: x[0])
(2, 'c')
>>> test = [(1, "a"), (1, "b"), (2, "d"), (2, "c")]
>>> max(test, key=lambda x: x[0])
(2, 'd')
>>> min(test, key=lambda x: x[0])
(1, 'a')
>>> test = [(1, "b"), (1, "a"), (2, "d"), (2, "c")]
>>> min(test, key=lambda x: x[0])
(1, 'b')
And Jeremy's excellent sleuthing confirms that this is indeed the case.
It picks the first element it sees. See the documentation for max()
:
If multiple items are maximal, the function returns the first one encountered. This is consistent with other sort-stability preserving tools such as
sorted(iterable, key=keyfunc, reverse=True)[0]
andheapq.nlargest(1, iterable, key=keyfunc)
.
In the source code this is implemented in ./Python/bltinmodule.c
by builtin_max
, which wraps the more general min_max
function.
min_max
will iterate through the values and use PyObject_RichCompareBool
to see if they are greater than the current value. If so, the greater value replaces it. Equal values will be skipped over.
The result is that the first maximum will be chosen in the case of a tie.