Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

max

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?

like image 853
Double AA Avatar asked Jul 21 '11 21:07

Double AA


People also ask

Does Max function work on strings in Python?

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.

What is the maximum number in Python?

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 do you find the maximum of a data set in Python?

“how to find max value in dataframe python” Code Answer'sdf. max() #max() gives you the maximum value in the series. df.


1 Answers

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.

like image 100
Jeremy Avatar answered Sep 24 '22 01:09

Jeremy