2

Is there something in Python that guarantees that the same item is always selected from an iterable when you use min/max with a key?

e.g.

>>> l = ['aaaaaa', 'bbbbbb', 'cc']
>>> max(l)
'cc'
>>> max(l, key=len)
'aaaaaa'

Does Python guarantee to return the first such object that has the maximum value according to the key function?

The first such object for min makes sense, but for max maybe the last such object would make more sense:

>>> sorted(l, key=len)[-1]
'bbbbbb'

I think this is because Python sorting is stable. So maybe my question is really, is there an equivalent concept to "stable" for min/max functions, and does Python follow it?

Community
  • 1
  • 1
pfctdayelise
  • 5,115
  • 3
  • 32
  • 52

0 Answers0