I'm trying to understand what happened in the following line:
print(max([1, -2, 3, -1], key=lambda x:(-abs(x), x), default=0))
My understanding is, the lambda will return a tuple for each element in the list [1, -2, 3, -1].
But how can a list be compared with a tuple?
And why the output is 1, instead of 3 ?
I've tried
print(max([1, -2, 3, -1], key=(-1, 1), default=0))
But it said uple is not callable
The key to understand the problem here is the key function used. If it's hard to understand, i recommend you to read this and play with sort rather max (cause sort will give you a informational anwser)
My understanding:
Step 1. the lambda function convert a = [1, -2, 3, -1]
to a new one b = [(-1, 1), (-2, -2), (-3, 3), (-1, 1)]
Step 2. max/sort will deal with the new listb
. It will first compare the first element, if it's tied, compare the second
Step3. convert the sorted(b)
in terms of a