Why does max() in this case return 7?

85 Views Asked by At
l = [7, 9, 5, 6, 13, 5, 15, 3]
t = max(l, key=lambda g:g if g%9==1 else 0)

t is the maximum element of l, whose remainder of the division by 9 is 1.

In this case, t equals 7. But this list doesn't have any elements whose remainder of the division by 9 is 1 at all! Why doesn't t equal 0?

3

There are 3 best solutions below

1
C_Z_ On BEST ANSWER

The lambda calculates the key for each value to be 0, and so with all elements having an equivalent key, the first element is returned.

The lambda is simply used to calculate the value for comparison, it does not convert the value that is returned.

0
OneCricketeer On

this list doesn't have any elements whose remainder of the division by 9 is 1 at all

max() will throw an error on an empty sequence, by the way; it would not return 0. If you wanted to filter the elements then get the max, you'd write that this way

t = 0
try:
    t = max(filter(lambda g: g % 9 == 1, l))
except ValueError:
    print('No values in the list have a remainder of 1, when divided by 9')
0
chepner On

Look at the keys actually being compared to one another:

>>> [x if x % 9 == 1 else 0 for x in [7, 9, 5, 6, 13, 5, 15, 3]]
[0, 0, 0, 0, 0, 0, 0, 0]

According to the key, no later value is larger than 7 (even though they are all as large as 7), so 7 is the result.

If any (positive) value in the list were congruent to 1 modulo 9, then max would return the first such value instead of 7.

>>> l = [7, 9, 5, 6, 13, 5, 15, 3, 10]
>>> max(l, key=lambda g:g if g%9==1 else 0)
10

It just so happens that the key can only return a non-negative value that equal to 0 or greater than 9. (-8 % 9 == 1, but then the key is -8 < 7.)