Search code examples
pythonlambdamax

Problems with understanding this use of lambda with max


I am currently trying to learn more about lambda functions and ran into the following string of code:

max_val = max(list_val, key = lambda i: (isinstance(i, int), i))

What does this part in the code actually mean/do:

(isinstance(i, int), i)

I do know what isinstance's purpose is but what is the second i doing here and what are the brackets around this whole thing doing?


Solution

  • The function returned by the following lambda expression:

    lambda i: (isinstance(i, int), i)
    

    is the same as the function that is assigned to f by the following def statement:

    def f(i):
        return (isinstance(i, int), i)
    

    The return value of the function (which takes i as an argument) is a tuple where the first element is a bool indicating whether i is an int, and the second element is i itself:

    >>> f(5)
    (True, 5)
    >>> f("foo")
    (False, 'foo')
    

    Tuples are compared in order of their elements, so in the context of the max call, this means that you'll get the largest int value (because True is "greater than" False), and will get the largest of whatever other type of value you have only if there are no int values.