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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With