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'
Answer from Ashwini Chaudhary on Stack Overflow
Top answer
1 of 8
420

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'
2 of 8
25

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
🌐
Programiz
programiz.com › python-programming › methods › built-in › max
Python max()
key (optional) - key function where the iterables are passed and comparison is performed based on its return value · default (optional) - default value if the given iterable is empty · max() returns the largest element from an iterable. ... If the items in an iterable are strings, the largest ...
Discussions

Confused about using max() to find the max value of a dict. See code example
key is a keyword argument for max which specifies how the max value is determined. In this case the code prints the key in the dictionary which holds the highest value. In other words, max iterates over dict (not a good idea to use built-in names btw), getting the keys, and then it keeps track of the values provided by dict.get(key) to determine the key with the highest value. Since an example is worth a thousand words, here's an old Gist I wrote years ago that effectively implements max. More on reddit.com
🌐 r/learnpython
7
1
November 2, 2023
Allow `min()` and `max()` to return both the key and value - Ideas - Discussions on Python.org
Problem Currently, min() and max() return only the minimum/maximum value, or in cases where the input is a mapping (like a dictionary), only the key. There are many situations where both the value and the associated key or object are needed. This leads to redundant code where users have to ... More on discuss.python.org
🌐 discuss.python.org
0
September 5, 2024
numpy - How to understand the key in python max function - Stack Overflow
The numpy array is in fact the only element inside the python list whose max element is being computed ... @inspectorG4dget It also confuses me. :-) Is that max() always output the original element in its input arg1? ... You have a list with a single element. No matter what that element is (or what the key ... More on stackoverflow.com
🌐 stackoverflow.com
Why is this working? [Getting key of max value from dict]
Functions are objects that can be stored and passed like any other object: stats = {1: 2} f = stats.get # Not called print(f(1)) # Prints 2 It's passing the uncalled get method to max, and then max calls it internally. More on reddit.com
🌐 r/pythonhelp
3
2
September 24, 2022
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-max-function
Python - max() function - GeeksforGeeks
July 15, 2025 - In this code, there is a list of strings, "string_list," containing ["Geeks", "for", "Geek"]. It utilizes the max() function with the key=len argument, which compares the strings based on their lengths.
🌐
Hyperskill
hyperskill.org › university › python › max-in-python
Python max() Function — Syntax, key Parameter & Examples
August 10, 2026 - The max() function finds the maximum value among elements of an iterable or a series of arguments. It returns the largest item based on the default ordering or a custom ordering specified by the optional key parameter. When used with iterables like lists or tuples, the function compares the ...
🌐
LabEx
labex.io › tutorials › python-how-to-use-a-custom-key-in-the-max-function-in-python-398075
How to use a custom key in the max function in Python | LabEx
... iterable: An iterable (such ... more arguments, from which the largest will be returned. key: An optional function that serves as a key for the comparison....
🌐
datagy
datagy.io › home › python posts › python: get dictionary key with the max value (4 ways)
Python: Get Dictionary Key with the Max Value (4 Ways) • datagy
February 23, 2022 - The Quick Answer: Use the max() function to get the dictionary key with the max values ... Dictionaries in Python are one of the main, built-in data structures. They are collections of items, each consisting of a key:value pairs.
Find elsewhere
🌐
Python.org
discuss.python.org › ideas
Allow `min()` and `max()` to return both the key and value - Ideas - Discussions on Python.org
September 5, 2024 - Problem Currently, min() and max() return only the minimum/maximum value, or in cases where the input is a mapping (like a dictionary), only the key. There are many situations where both the value and the associated key …
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-keys-with-maximum-value
Keys with Maximum Value - Python - GeeksforGeeks
November 18, 2025 - This method first finds the highest value in the dictionary using max(), then iterates through all keys and collects those whose value matches the maximum.
Top answer
1 of 4
7

The example code shows a python list (x) which contains one single numpy array with 10 elements. The max of that list (regardless of the key) is that numpy array.

What does key do?

This is a function that computes a value to each element in the list that is different from its representational value. Whichever element has the largest value as computed by this function is the max of the list.

For example:

In [109]: L = [str(i) for i in range(20)]                                                                                                                                                                                                                                     

In [110]: L                                                                                                                                                                                                                                                                   
Out[110]: 
['0',
 '1',
 '2',
 '3',
 '4',
 '5',
 '6',
 '7',
 '8',
 '9',
 '10',
 '11',
 '12',
 '13',
 '14',
 '15',
 '16',
 '17',
 '18',
 '19']

In [111]: max(L)                                                                                                                                                                                                                                                              
Out[111]: '9'  # '9' is the lexicographically max string

In [112]: max(L, key=int)                                                                                                                                                                                                                                                     
Out[112]: '19'  # 19 is the numerically max number, int('19') has this value

The example you have would have been clearer were it written like this instead:

In [106]: L = [np.array(range(i)) for i in range(1, 11)]                                                                                                                                                                                                                      

In [107]: L                                                                                                                                                                                                                                                                   
Out[107]: 
[array([0]),
 array([0, 1]),
 array([0, 1, 2]),
 array([0, 1, 2, 3]),
 array([0, 1, 2, 3, 4]),
 array([0, 1, 2, 3, 4, 5]),
 array([0, 1, 2, 3, 4, 5, 6]),
 array([0, 1, 2, 3, 4, 5, 6, 7]),
 array([0, 1, 2, 3, 4, 5, 6, 7, 8]),
 array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])]

In [108]: max(L, key=np.size)                                                                                                                                                                                                                                                 
Out[108]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
2 of 4
1

Your first problem is that you are using the range(10), which goes up to 10, but doesn't include the number 10. The way to go here is x =[np.array(range(11))]

And to get the max of this, using the numpy documentation, you can use np.amax, which can be done like this: res = np.amax(x) and it should work

https://numpy.org/doc/stable/reference/generated/numpy.amax.html - link for documentation.

🌐
All About AI-ML
indhumathychelliah.com › 2020 › 08 › 17 › how-to-use-key-function-in-max-and-min-in-python
How to Use Key Function in Max() and Min() in Python – All About AI-ML
January 2, 2022 - Refer to my story for how to use the key function in the sorted() function. Return the largest item in an iterable or the largest of two or more arguments. If one item is given, it should be iterable.
🌐
GeeksforGeeks
geeksforgeeks.org › python-get-key-with-maximum-value-in-dictionary
Get key with maximum value in Dictionary - GeeksforGeeks
However, if the key is not present in the dictionary we need to handle this gracefully to avoid errors. For example, consider the dictionary : d = {'name': 'Alice', 'age': 25, 'city': 'New York'} if we try t · 3 min read Python - Maximum Value in Nested Dictionary
Published: May 6, 2025
🌐
PythonHello
pythonhello.com › problems › dict › get-key-with-max-value-in-dict
Getting the Key with the Maximum Value in a Dictionary in ...
The max() function takes an iterable as an argument and returns the maximum value. To get the key with the maximum value in a dictionary, we can pass the dictionary to the max() function as an iterable and use the key parameter to specify the ...
🌐
Reddit
reddit.com › r/pythonhelp › why is this working? [getting key of max value from dict]
r/pythonhelp on Reddit: Why is this working? [Getting key of max value from dict]
September 24, 2022 -

Hey all,

I was looking for how to achieve this and found this post which did the trick, specifically the suggestion to do it like max(stats, key=stats.get)

That's good news - bad news is I don't understand how that's working and I don't like that feeling :D

More specifically, I am confused by how are we able to use .get on a dictionary and not .get(key)? Also, if there are multiple elements in the max, shouldn't it compare them all?

W3 says the syntax for each of those two is:

dictionary.get(keyname, value) - We don't do that here
max(n1, n2, n3, ...) - We don't do that here, either

So how does this approach work? I am glad I got a quick and neat solution, but feel stupid copying it blindly.

🌐
GeeksforGeeks
geeksforgeeks.org › python › python-get-key-with-maximum-value-in-dictionary
Get key with maximum value in Dictionary - Python
Explanation: max() function is used to find the maximum element where key=d.get ensures the comparison is made based on the values (not keys).
Published: July 11, 2025
🌐
Medium
medium.com › analytics-vidhya › how-to-use-key-function-in-max-and-min-in-python-1fdbd661c59c
How to Use Key Function in Max() and Min() in Python | by Indhumathy Chelliah | Analytics Vidhya | Medium
January 17, 2024 - If two or more positional arguments are provided, the largest of the positional arguments is returned. max(arg1, arg2, *args[, key]) 78K followers · ·Last published Dec 16, 2025 · Analytics Vidhya is a community of Generative AI and Data Science professionals. We are building the next-gen data science ecosystem https://www.analyticsvidhya.com · 1.4K followers · ·230 following · Machine Learning | Python |R | Tableau | 1.5 M Views ·
🌐
w3resource
w3resource.com › python-exercises › dictionary › python-data-type-dictionary-exercise-80.php
Python: Find the key of the maximum, minimum value in a dictionary - w3resource
June 28, 2025 - Write a Python program to use dictionary comprehension and the max() function to extract the key with the largest value.
🌐
Tutorial Gateway
tutorialgateway.org › python-max-function
Python max Function
December 29, 2018 - Generally, the max function key value is assigned to a default value. However, it accepts funcs. For example, key = function_name.
🌐
ThePythonGuru
thepythonguru.com › python-builtin-functions › max › index.html
Python max() function - ThePythonGuru.com
# find largest item in the string print(max("abcDEF")) # find largest item in the list print(max([2, 1, 4, 3])) # find largest item in the tuple print(max(("one", "two", "three"))) 'two' # find largest item in the dict print(max({1: "one", 2: "two", 3: "three"})) 3 # empty iterable causes ValueError # print(max([])) # supressing the error with default value print(max([], default=0)) ... Trying to find largest value among the objects of different types causes an error. To customize the sort order we use the key named argument.