Reputation: 13
When using Python max() function with the "key" argument and passing on this argument a function that calculates modulo of the given integer number I don't get desired results. Here are the code snippet and results for two different lists consist of integer numbers.
def mod_2(x):
return x % 2
list1 = [1, 2, 3]
list2 = [3, 2, 1]
print(max(list1, key=mod_2))
print(max(list2, key=mod_2))
The results are 1 and 3 respectively. Should not the result of the first print be 3? Or, does the max() function just give the first occurrence of the two same numbers by nature? The results of mod_2 operations for both numbers are the same (since 3 % 2 = 1 % 2). How does max() function decide in such a condition actually?
Upvotes: 0
Views: 144
Reputation: 143
When the Max function give two same numbers, it selects the first number
Upvotes: 0
Reputation: 5520
You ask:
does the max() function just give the first occurrence of the two same numbers by nature?
How is the documentation saying
If multiple items are maximal, the function returns the first one encountered.
unclear?
Upvotes: 0