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?
The max() method can also be used with strings. In the above example, the largest string based on the alphabetical order is returned. In the case of strings, the highest value can also be returned based on other parameters like the length of the string if the key parameter is used.
In the approach above we assume that 999999 is the maximum possible value in our list and compare it with other elements to update when a value lesser than it is found.
“how to find max value in dataframe python” Code Answer'sdf. max() #max() gives you the maximum value in the series. df.
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