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
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
python - Getting key with maximum value in dictionary? - Stack Overflow
Interestingly, a solution that's ... in both Python 2 and 3 is: max(stats, key=lambda key: stats[key]) 2015-05-05T21:56:39.22Z+00:00 ... Honestly I think that the comments have the cleaner and better solution. 2019-09-19T16:35:51.743Z+00:00 ... Save this answer. ... Show activity on this post. I have tested MANY variants, and this is the fastest way to return the key of dict with the max ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
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....
🌐
ThePythonGuru
thepythonguru.com › python-builtin-functions › max › index.html
Python max() function - ThePythonGuru.com
Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now! Updated on Jan 07, 2020 · The max() function returns the largest of the input values. Its syntax is as follows: max(iterable[, default=obj, key=func]) -> value ·
🌐
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.
🌐
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 - If two or more positional arguments are provided, the largest of the positional arguments is returned. max(arg1, arg2, *args[, key])
Find elsewhere
🌐
Hyperskill
hyperskill.org › university › python › max-in-python
Python max() Function — Syntax, key Parameter & Examples
August 10, 2026 - Additionally, max() can handle different object types and is not limited to simple numerical values. 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 ...
🌐
GeeksforGeeks
geeksforgeeks.org › python-get-key-with-maximum-value-in-dictionary
Get key with maximum value in Dictionary - GeeksforGeeks
We are given a dictionary and our task is to retrieve the value associated with a given key. 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
🌐
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])
🌐
Real Python
realpython.com › ref › builtin-functions › max
max() | Python’s Built-in Functions – Real Python
Suppose you have a dictionary of product prices and want to identify the most expensive product. You can use max() with the .items() method and a lambda function as the key argument:
🌐
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 finds the maximum value, then uses filter() to keep only those keys whose values match that maximum, with a lambda function specifying the condition. ... d = {'Gfg': 2, 'for': 1, 'CS': 2} mx = max(d.values()) res = list(filter(lambda ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-get-key-with-maximum-value-in-dictionary
Get key with maximum value in Dictionary - Python
In this method we will use the built-in max() function to identify the key with the highest value in the dictionary and by specifying key=d.get we can ensure that the comparison is based on the dictionary values rather than the keys.
Published: July 11, 2025
🌐
Learn By Example
learnbyexample.org › python-max-function
Python max() Function - Learn By Example
April 20, 2020 - # Specify default value '0' L = [] x = max(L, default='0') print(x) # Prints 0 · With optional key parameter, you can specify custom comparison criteria to find maximum value.
🌐
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.

🌐
PythonHello
pythonhello.com › problems › dict › get-key-with-max-value-in-dict
Getting the Key with the Maximum Value in a Dictionary in ...
To get the key with the maximum value in a dictionary, we can pass the dictionary to the sorted() function as an iterable and use the key parameter to specify the key function, which returns the value to be used for the comparison.
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.

🌐
YouTube
youtube.com › the python oracle
python max function using 'key' and lambda expression - YouTube
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn--Music by Eric Matyashttps://www.soundimage.orgTrack title: Puzzle M...
Published: March 2, 2023
Views: 62