[issue41276] Min / Max returns different values depending on parameter order

Steven D'Aprano report at bugs.python.org
Sat Jul 11 00:32:06 EDT 2020


Steven D'Aprano <steve+python at pearwood.info> added the comment:

In your first example, `min([(-5, 2), (0, 2)])` the min() function compares the two tuples and finds that the first one is lexicographically smaller:

    py> (-5, 2) < (0, 2)
    True

so (-5, 2) is considered the minimum. In the second example, using the key function compares 2 with 2, but since they are equal, the *first* tuple wins and is considered the minimum, and so using the key function doesn't change the result.

In your third example, after reversing the list, you have `min([(0, 2), (-5, 2)])` and the min() function compares the two tuples and finds the *second* tuple is the smaller:

    py> (0, 2) < (-5, 2)
    False

But in the fourth example, using the key function, yet again the comparison compares 2 with 2 and finds them equal, and so the *first* tuple wins and (0, 2) is declared the minimum.

When using the key function, only the second item of the tuple is looked at; the first item is ignored. So the difference between 0 and -5 is irrelevant, and the tie is decided by which element was seen first.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue41276>
_______________________________________


More information about the Python-bugs-list mailing list