Which maximum does Python pick in the case of a tie?

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] and heapq.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.

Leave a Comment