Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python max and min functions - greedy? [duplicate]

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 931
Double AA Avatar asked Nov 25 '22 05:11

Double AA


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 81
Jeremy Avatar answered Jun 19 '23 13:06

Jeremy