When I try to find out the index of the largest element in a list by using the key keyword in the python3 built-in function, max, I find it doesn't necessarily return the index of the max element.
For example,
array = [float('nan'), 1.0, 3.0, 2.0, float('nan')]
max(range(len(array)), key=lambda i: array[i])
The above code yields 0 instead of 2 as expected.
Seemingly Related Questions
CodePudding user response:
The code for max (and min) works roughly in the following way:
def my_max(sequence, key=None, default=None):
max_value = None
max_item = None
for item in sequence:
if key is not None:
value = key(item)
else:
value = item
if max_item is None:
max_item = item
max_value = value
elif value > max_value:
max_value = value
max_item = item
if max_item is None:
if default is None:
raise ValueError
return default
return max_item
The actual source code (in C) can be found here.
The main takeaway here is that on the first iteration, for your given input, max_item is set to 0, and max_value is set to nan. One important thing to note is that the operations <, <=, >, >=, and == will always return False when a nan is involved, as defined by the IEEE 754 floating point standard (example source). This means that no greater element will ever be found after the first item, and hence 0 is returned.
