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

max, python

Solution

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.

Problem

When using the `max()` function in Python to find the maximum value in a list (or tuple, dict etc.) and there is a tie for maximum value, which one does Python pick? Is it random? This is relevant if, for instance, one has a list of tuples and one selects a maximum (using a `key=`) based on the first element of the tuple but there are different second elements. How does Python decide which one to pick as the maximum?

Original source

Related problems