I'm trying to understand how the key argument works in the max function, coming from a problem of finding the closest integer to 0 from a list, and using the positive value in case of having the same positive and negative value in the list.
I have found this to be an efficient solution online, given a list of integers x:
print(max(a, key=lambda x: (-abs(x), x), default=0))
This returns a single integer, where I would expect to return a tuple, given that the lambda will transform every element of x into a tuple, then I did this:
b = list(map(lambda x: (-abs(x), x), a))
max(b)
And this second example returns a tuple. Why does the first one return a single elements when it is comparing tuples generated by the lambda?
You are comparing two different things.
For your first case, if we look at the docs: https://docs.python.org/3/library/functions.html#max
Which means that the key
lambda x: (-abs(x), x)
is a ordering function, which means that for everyx
in iterablea
,(-abs(x), x)
is evaluated and is used to order the items for finding out the maximum element of the iterator, and according to that ordering,1
is the maximum elementFor the second case, if we look at the docs: https://docs.python.org/3/library/functions.html#map
Which means that the function
lambda x: (-abs(x), x)
is applied to every elementx
ofa
, so we get back(-abs(x), x)
for every x, and themax
is applied on the updated iterator, which is the largest tuple(-1,1)