268

I come from OOP background and trying to learn python. I am using the max function which uses a lambda expression to return the instance of type Player having maximum totalScore among the list players.

def winner():
    w = max(players, key=lambda p: p.totalScore)

The function correctly returns instance of type Player having maximum totalScore. I am confused about the following three things:

  1. How does the max function work? What are the arguments it is taking? I looked at the documentation but failed to understand.
  2. What is use of the keyword key in max function? I know it is also used in context of sort function
  3. Meaning of the lambda expression? How to read them? How do they work?

These are all very noobish conceptual questions but will help me understand the language. It would help if you could give examples to explain. Thanks

5
  • Which Python version? Commented Aug 18, 2013 at 7:35
  • 5
    Have you consulted the documentation?
    – Inbar Rose
    Commented Aug 18, 2013 at 7:36
  • @charmlessCoin python 2.7.5
    – Vijay
    Commented Aug 18, 2013 at 7:36
  • 4
    @InbarRose I checked the documentation for max function. Didn't really understand it.
    – Vijay
    Commented Aug 18, 2013 at 7:38
  • 26
    @InbarRose This page is actually now the top result on Google for python max lambda and perhaps may actually be more helpful for new users.
    – Mark
    Commented Jan 9, 2015 at 5:40

8 Answers 8

407

lambda is an anonymous function, it is equivalent to:

def func(p):
   return p.totalScore     

Now max becomes:

max(players, key=func)

But as def statements are compound statements they can't be used where an expression is required, that's why sometimes lambda's are used.

Note that lambda is equivalent to what you'd put in a return statement of a def. Thus, you can't use statements inside a lambda, only expressions are allowed.


What does max do?

max(a, b, c, ...[, key=func]) -> value

With a single iterable argument, return its largest item. With two or more arguments, return the largest argument.

So, it simply returns the object that is the largest.


How does key work?

By default in Python 2 key compares items based on a set of rules based on the type of the objects (for example a string is always greater than an integer).

To modify the object before comparison, or to compare based on a particular attribute/index, you've to use the key argument.

Example 1:

A simple example, suppose you have a list of numbers in string form, but you want to compare those items by their integer value.

>>> lis = ['1', '100', '111', '2']

Here max compares the items using their original values (strings are compared lexicographically so you'd get '2' as output) :

>>> max(lis)
'2'

To compare the items by their integer value use key with a simple lambda:

>>> max(lis, key=lambda x:int(x))  # compare `int` version of each item
'111'

Example 2: Applying max to a list of tuples.

>>> lis = [(1,'a'), (3,'c'), (4,'e'), (-1,'z')]

By default max will compare the items by the first index. If the first index is the same then it'll compare the second index. As in my example, all items have a unique first index, so you'd get this as the answer:

>>> max(lis)
(4, 'e')

But, what if you wanted to compare each item by the value at index 1? Simple: use lambda:

>>> max(lis, key = lambda x: x[1])
(-1, 'z')

Comparing items in an iterable that contains objects of different type:

List with mixed items:

lis = ['1','100','111','2', 2, 2.57]

In Python 2 it is possible to compare items of two different types:

>>> max(lis)  # works in Python 2
'2'
>>> max(lis, key=lambda x: int(x))  # compare integer version of each item
'111'

But in Python 3 you can't do that any more:

>>> lis = ['1', '100', '111', '2', 2, 2.57]
>>> max(lis)
Traceback (most recent call last):
  File "<ipython-input-2-0ce0a02693e4>", line 1, in <module>
    max(lis)
TypeError: unorderable types: int() > str()

But this works, as we are comparing integer version of each object:

>>> max(lis, key=lambda x: int(x))  # or simply `max(lis, key=int)`
'111'
5
  • 1
    I think this is old, but I had a question in regards to this. I see for the lambda function, the variable x or i or anything else always represents the value at that index in the list. Is this iteration done by the max function or by the lambda? Do lambda functions always iterate over the possible values? For example: lengths = map(lambda word: len(word), words) where words=['It', 'is', 'raining', 'cats', 'and', 'dogs'] I see that the lambda is iterating over every word in the list. Does it always do this?
    – Mo2
    Commented Oct 10, 2014 at 0:57
  • 2
    @Mo2 Iteration is done by max not lambda(key arg is optional), and during iteration each item is passed to the function specified in key and the returned value is then used for comparison. Commented Oct 10, 2014 at 3:44
  • 4
    Just for the people who came here by googling "max key parameter". max(lis, key=lambda x:int(x)) can be simplified as max(lis, key=int). Python has a built-in function, int(). Similarly you can use any other built-in functions as a key argument. For instance you can get the longest string from lis=['a', 'aa', 'aaa'] by max(lis, key=len)
    – YOUNG
    Commented Aug 19, 2015 at 6:43
  • 2
    @YOUNG We can use any function as key argument not just builtin functions, the only condition is that the function should accept the items passed to it by max, min, sorted etc properly. Plus I have mentioned max(lis, key=int) right at the end. :-) Commented Aug 19, 2015 at 6:55
  • @Ashwini Chaudhary.. suppose If I have a list like [1,2,3,4,5]. here all the items are different. I am using given function max(set(mylist),key=mylist.count) to find the most frequent items. since in this case there's no element which is repeating. it's returning the lowest item. Can we do something so that it returns zero or null in such case. Commented Oct 16, 2019 at 12:22
24

Strongly simplified version of max:

def max(items, key=lambda x: x):
    current = item[0]
    for item in items:
        if key(item) > key(current):
            current = item
    return current

Regarding lambda:

>>> ident = lambda x: x
>>> ident(3)
3
>>> ident(5)
5

>>> times_two = lambda x: 2*x
>>> times_two(2)
4
3
  • 1
    This version will be wrong in case input() is used in lambda.
    – Shreyansh
    Commented Apr 19, 2021 at 7:12
  • so, that "key" is not the key in dict, it is "calculate function that affect value before comparsion", so it is a function as input....
    – Fenix Lam
    Commented Apr 29, 2021 at 3:17
  • @Shreyansh the function I have here is just for intuition as to what max does at a high level, it doesn't call key with exactly the same pattern as stdlib. if your function has side effects or is indeterministic, things can diverge. Commented Apr 19, 2023 at 14:37
14

max function is used to get the maximum out of an iterable.

The iterators may be lists, tuples, dict objects, etc. Or even custom objects as in the example you provided.

max(iterable[, key=func]) -> value
max(a, b, c, ...[, key=func]) -> value

With a single iterable argument, return its largest item.
With two or more arguments, return the largest argument.

So, the key=func basically allows us to pass an optional argument key to the function on whose basis is the given iterator/arguments are sorted & the maximum is returned.

lambda is a python keyword that acts as a pseudo function. So, when you pass player object to it, it will return player.totalScore. Thus, the iterable passed over to function max will sort according to the key totalScore of the player objects given to it & will return the player who has maximum totalScore.

If no key argument is provided, the maximum is returned according to default Python orderings.

Examples -

max(1, 3, 5, 7)
>>>7
max([1, 3, 5, 7])
>>>7

people = [('Barack', 'Obama'), ('Oprah', 'Winfrey'), ('Mahatma', 'Gandhi')]
max(people, key=lambda x: x[1])
>>>('Oprah', 'Winfrey')
11

How does the max function work?

It looks for the "largest" item in an iterable. I'll assume that you can look up what that is, but if not, it's something you can loop over, i.e. a list or string.

What is use of the keyword key in max function? I know it is also used in context of sort function

Key is a lambda function that will tell max which objects in the iterable are larger than others. Say if you were sorting some object that you created yourself, and not something obvious, like integers.

Meaning of the lambda expression? How to read them? How do they work?

That's sort of a larger question. In simple terms, a lambda is a function you can pass around, and have other pieces of code use it. Take this for example:

def sum(a, b, f):
    return (f(a) + f(b))

This takes two objects, a and b, and a function f. It calls f() on each object, then adds them together. So look at this call:

>>> sum(2, 2, lambda a:  a * 2)
8

sum() takes 2, and calls the lambda expression on it. So f(a) becomes 2 * 2, which becomes 4. It then does this for b, and adds the two together.

In not so simple terms, lambdas come from lambda calculus, which is the idea of a function that returns a function; a very cool math concept for expressing computation. You can read about that here, and then actually understand it here.

It's probably better to read about this a little more, as lambdas can be confusing, and it's not immediately obvious how useful they are. Check here.

6

According to the documentation:

max(iterable[, key])
max(arg1, arg2, *args[, key])
Return the largest item in an iterable or the largest of two or more arguments.

If one positional argument is provided, iterable must be a non-empty iterable (such as a non-empty string, tuple or list). The largest item in the iterable is returned. If two or more positional arguments are provided, the largest of the positional arguments is returned.

The optional key argument specifies a one-argument ordering function like that used for list.sort(). The key argument, if supplied, must be in keyword form (for example, max(a,b,c,key=func)).

What this is saying is that in your case, you are providing a list, in this case players. Then the max function will iterate over all the items in the list and compare them to each other to get a "maximum".

As you can imagine, with a complex object like a player determining its value for comparison is tricky, so you are given the key argument to determine how the max function will decide the value of each player. In this case, you are using a lambda function to say "for each p in players get p.totalscore and use that as his value for comparison".

6

max is built in function which takes first argument an iterable (like list or tuple)

keyword argument key has it's default value None but it accept function to evaluate, consider it as wrapper which evaluates iterable based on function

Consider this example dictionary:

d = {'aim':99, 'aid': 45, 'axe': 59, 'big': 9, 'short': 995, 'sin':12, 'sword':1, 'friend':1000, 'artwork':23}

Ex:

>>> max(d.keys())
'sword'

As you can see if you only pass the iterable without kwarg(a function to key) it is returning maximum value of key(alphabetically)

Ex. Instead of finding max value of key alphabetically you might need to find max key by length of key:

>>>max(d.keys(), key=lambda x: len(x))
'artwork'

in this example lambda function is returning length of key which will be iterated hence while evaluating values instead of considering alphabetically it will keep track of max length of key and returns key which has max length

Ex.

>>> max(d.keys(), key=lambda x: d[x])
'friend'

in this example lambda function is returning value of corresponding dictionary key which has maximum value

1

This helped me to understand how this pattern works. Think of the key as a transform function/comparison metric.

max(data, lambda x: transform_function(x))

What does this mean. Imagine we have a list of numbers [1, 2, 3, 4, 5]. And our task is to find the value for which the sine results in the largest value.

Instead of applying the max function to the numbers list, we transform every value with our transform function (here sin)

1 -> sin(1)
2 -> sin(2)
3 -> sin(3)
4 -> sin(4)
5 -> sin(5)

Now, we apply the max function on the transformed values. Which will give us sin(2), and this is resulting from the input 2, so the max(numbers, lambda x: sin(x)) will return 2.

Let us apply this idea to a more complicated situation. Consider the following dictionary (e.g. cities with three temperature measurements):

cities = {
    "New York": [10, 12, 13],
    "Los Angeles": [14, 15, 16],
    "Washington": [8, 5, -1],
}

Our goal is to find the city with the highest temperature (which should be Los Angeles). What is a proper transformation that we need to apply? To put it into words: We want to see the max of the temperatures = cities[city], hence max(cities[city]) should be our transform. So we need to do the following.

max(cities, key=lambda city: max(cities[city]))

You could even do this with nested dictionaries.

cities: dict = {
    "New York": {
        "temperatures": [1, 2, 9],
        "populations": [10000, 20000, 30000],
    },
    "Los Angeles": {
        "temperatures": [4, 5, 4],
        "populations": [40000, 50000, 60000],
    },
    "Washington": {
        "temperatures": [1, 0, -1],
        "populations": [10000, 1000, 0],
    }
}
    
max(cities, key=lambda city: max(cities[city]["populations"]))
0

Assuming that people who come to this page actually want to know what is key= inside len(), here is the simple answer:

len() counts the length of the object. If we specify len as a key function in min(), max(), it will return the smallest/largest item based on their length.

food = ['bread', 'tea', 'banana', 'kiwi', 'tomato']

print(max(food, key=len))   # banana
print(min(food, key=len))   # tea

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.