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
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › python max lambda
Python Max Lambda - Spark By {Examples}
May 31, 2024 - How to find the max value using lambda expression in Python? You can use the max() function to find the maximum value from a given iterable, such as a
🌐
Kodeclik
kodeclik.com › python-max-lambda
How to find the max using a Python lambda
September 19, 2024 - To find the maximum element in any Python iterable with a custom meaning for maximum, pass a lambda function as a parameter to the max() built-in function specifying the key property to be used when comparing elements.
🌐
Python Basics
python-basics-tutorial.readthedocs.io › en › latest › functions › lambda.html
Lambda functions - Python Basics
In this case, the max() function ... is to be determined. Using a lambda function that converts each string into an integer, max can compare the numerical values to determine the expected result....
🌐
OpenGenus
iq.opengenus.org › python-max-lambda
Python Max Lambda [6 ways]
November 26, 2022 - In this article, we have explained how to use lambda with max() built-in function in Python to find the maximum element in any iterable with custom objects. Additionally, we have presented how to implement max from scratch using lambda without using any built-in function.
🌐
EyeHunts
tutorial.eyehunts.com › home › python max lambda
Python max lambda
September 6, 2023 - In Python, the max() function is used to find the maximum value within an iterable (e.g., a list, tuple, or other iterable). You can use a lambda function with the max() function to customize the criteria by which the maximum value is determined.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-program-maximum-of-three-number-using-lambda
Python Program Maximum of Three Number using Lambda - GeeksforGeeks
July 23, 2025 - Below are some of the ways by which we can find the maximum among three numbers in Python. ... The below code defines a lambda function find_max that takes three parameters and uses the max() function to determine the maximum among them.
🌐
Delft Stack
delftstack.com › home › howto › python › find max value using lamba expression
How to Find Maximum and Minimum Value Using Lambda Expression in Python | Delft Stack
March 11, 2025 - In summary, using lambda expressions in Python to find maximum and minimum values is a straightforward yet powerful technique. By leveraging the max() and min() functions along with the key parameter, you can efficiently extract values based ...
Find elsewhere
🌐
Hyperskill
hyperskill.org › university › python › max-in-python
Python max() Function — Syntax, key Parameter & Examples
August 10, 2026 - Using a lambda function allows modifying how items in an iterable are compared based on specific conditions. ... students = [{'name': 'John', 'score': 80}, {'name': 'Jane', 'score': 95}, {'name': 'Tom', 'score': 75}] max_student = max(students, key=lambda student: student['score']) ...
🌐
Real Python
realpython.com › ref › builtin-functions › max
max() | Python’s Built-in Functions – Real Python
>>> prices = { ... "banana": 1.20, ... "pineapple": 0.89, ... "apple": 1.57, ... "grape": 2.45, ... } >>> max(prices.items(), key=lambda item: item[1]) ('grape', 2.45)
🌐
Learn By Example
learnbyexample.org › python-max-function
Python max() Function - Learn By Example
April 20, 2020 - # Find out who is the oldest student L = [('Sam', 35), ('Tom', 25), ('Bob', 30)] x = max(L, key=lambda student: student[1]) print(x) # Prints ('Sam', 35) Let’s create a list of students (custom object) and find out who is the oldest student.
🌐
YouTube
youtube.com › watch
Python Lambda Function | Finding Max Values in a List | NareshIT #lambdaexpression #python - YouTube
🚀 Enroll Now: https://shorturl.at/ZZNnt🌟 Join Our Free Demo On Python & Full Stack Python with Mr. Satish Gupta. 🗓️ Workshop Details:Date: 21th AugustTime...
Published: August 17, 2024
🌐
Markmeretzky
markmeretzky.com › python › list › max.html
max with lambda
""" import sys months = ["February", "August", "May"] m = max(months) print(f"m = {m}") sys.exit(0)
🌐
Codemia
codemia.io › home › knowledge hub › python max function using 'key' and lambda expression
python max function using 'key' and lambda expression | Codemia
September 24, 2025 - Mixing incomparable types in key output (for example int and str), which can raise errors. Using max() where full ordering is needed; in those cases sorted() may be more appropriate. max(..., key=...) is the idiomatic way to select the best element from complex data in Python, and lambda provides ...
🌐
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
🌐
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 - # define function to take second element def cmp_key(e): return e[1] l1 = [(1, 2, 3), (2, 1, 3), (11, 4, 2), (9, 1, 3)] # Based on user defined function print(min(l1, key=cmp_key)) # Output:(2,1,3) print(max(l1, key=cmp_key)) #Output:(11,4,2) We can mention the key function as a lambda function also.
🌐
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
In this example, the custom key function lambda person: person["score"] extracts the "score" value from each dictionary in the people list, and the max() function uses these scores to determine the person with the highest score. By leveraging custom keys, you can tailor the max() function to meet your specific needs and extract the largest item based on your desired criteria. The ability to use custom keys with the max() function in Python opens up a wide range of practical applications.
🌐
w3resource
w3resource.com › python-exercises › lambda › python-lambda-exercise-26.php
Python: Find the list with maximum and minimum length using lambda - w3resource
Write a Python program to identify the sublist with the highest average value and the one with the lowest average using lambda. Write a Python program to determine the list with the maximum number of unique elements and the one with the minimum using lambda.
🌐
w3resource
w3resource.com › python-exercises › lambda › python-lambda-exercise-29.php
Python: Find the maximum values in a given heterogeneous list using lambda - w3resource
July 12, 2025 - Write a Python program to find the longest element in a heterogeneous list based on length (for strings) or value (for numbers) using lambda.