How do keys work in min and max?
Question: I run through the following sequence of statements:

    
    
    >>> a =range(10)
    >>> min(a,key=lambda(x):x<5.3)
    6
    >>> max(a,key=lambda(x):x<5.3)
    0
    

The min and max give the exact opposite of what I was expecting. The python
documentation on min and max is pretty sketchy. Can anyone explain to me how
the "key" works? Thanks.


Answer: ## Explanation of the `key` argument

Key works like this:

    
    
    a_list = ['apple', 'banana', 'canary', 'doll', 'elephant']
    
    min(a_list, key=len)
    

returns `'doll'`, and

    
    
    max(a_list, key=len)
    

returns `'elephant'`

You provide it with a function, and it uses the minimum or maximum of the
results of the function applied to each item to determine which item to return
in the result.

## Application

If your function returns a boolean, like yours, for min it'll return the first
of the minimum of True or False, (which is False) which would be 6 or the
first of the max (True) which would be 0.

To see this:

    
    
    >>> a
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> import pprint
    >>> pprint.pprint(dict((i, i<5.3) for i in a))
    {0: True,
     1: True,
     2: True,
     3: True,
     4: True,
     5: True,
     6: False,
     7: False,
     8: False,
     9: False}
    

Why?

    
    
    >>> min([True, False])
    False
    >>> max([True, False])
    True
    

## Explanation

Why is `True` greater than `False`?

    
    
    >>> True == 1
    True
    >>> False == 0
    True
    >>> issubclass(bool, int)
    True
    

It turns out that `True` and `False` are very closely related to `1` and `0`.
They even evaluate the same respectively.

