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
🌐
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.
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
🌐
OpenGenus
iq.opengenus.org › python-max-lambda
Python Max Lambda [6 ways]
November 26, 2022 - Linear Search in Python using OOP Concepts · More Less Up · Get this book -> Problems on Array: For Interviews and Competitive Programming · 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.
🌐
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.
🌐
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 ...
🌐
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)
🌐
w3resource
w3resource.com › python-exercises › lambda › python-lambda-exercise-51.php
Python: Find the maximum and minimum values in a given list of tuples using lambda function - w3resource
# Define a function 'max_min_list_tuples' that finds the maximum and minimum values in a list of tuples def max_min_list_tuples(class_students): # Find the maximum value in 'class_students' using 'max' function with a lambda key function # Extract the second element (index 1) from each tuple and find the maximum value based on that return_max = max(class_students, key=lambda item: item[1])[1] # Find the minimum value in 'class_students' using 'min' function with a lambda key function # Extract the second element (index 1) from each tuple and find the minimum value based on that return_min = mi
Find elsewhere
🌐
w3resource
w3resource.com › python-exercises › lambda › python-lambda-exercise-26.php
Python: Find the list with maximum and minimum length using lambda - w3resource
# Define a function 'max_length_list' ... the maximum length using the 'max' function and a lambda function max_list = max(input_list, key=lambda i: len(i)) # Return a tuple containing the maximum length and the sublist with the ...
🌐
w3resource
w3resource.com › python-exercises › lambda › python-lambda-exercise-46.php
Python: Find all index positions of the maximum and minimum values in a given list using lambda - w3resource
July 12, 2025 - # Define a function 'position_max_min' ... specifies a lambda function to evaluate each element by its value max_result = max(enumerate(nums), key=(lambda x: x[1])) # Find the minimum value and its index in 'nums' using 'min' function ...
🌐
7starsea
tech.7starsea.com › post › 311
Python: usuage of lambda function in sort, max, min, map, filter, reduce - Aimin's Codebook
January 25, 2015 - ==== Examples of //lambda// function Convert a integer string to integer value {{{ lambda x:int(x) }}} Compare two values:x,y {{{ lambda x,y: x>y }}} Get the value with key for a dictionary {{{ lambda x: x['key'] }}} ==== Usuage of //lambda// function Suppose we have a list like: {{{ example=[{'key' : 6}, {'key' : 8}, {'key' : 9}, {'key' : 11}] }}} Get the maximum or minimum of //example// with respect to //key// {{{ max( example, key=lambda x: x['key'] ) min( example, key=lambda x: x['key'] ) }}} sort //exmple// with respect to //key// {{{ example.sort( key=lambda x: x['key'] ) example.sort(
🌐
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
🌐
Python Basics
python-basics-tutorial.readthedocs.io › en › latest › functions › lambda.html
Lambda functions - Python Basics
In this case, the max() function accepts the key argument, which defines how the size of each entry is to be determined. Using a lambda function that converts each string into an integer, max can compare the numerical values to determine the ...
🌐
Programiz
programiz.com › python-programming › methods › built-in › max
Python max()
max() returns the largest element from an iterable. ... If the items in an iterable are strings, the largest item (ordered alphabetically) is returned. languages = ["Python", "C Programming", "Java", "JavaScript"]
🌐
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.
🌐
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 - # Define a function 'max_val' that ... # 2. Second, sort lexicographically by the elements themselves max_val = max(list_val, key=lambda i: (isinstance(i, int), i)) # Return the maximum value found in the list return max_val # Create ...
🌐
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.
🌐
Daniel Lemire's blog
lemire.me › blog › 2004 › 11 › 25 › computing-argmax-fast-in-python
Computing argmax fast in Python – Daniel Lemire's blog
November 24, 2015 - from itertools import izip argmaxbad = lambda array,badindexes: max(ifilter(lambda t: t[1] not in badindexes,izip(array, xrange(len(array)))))[1] Python is amazingly easy.
🌐
Vultr Docs
docs.vultr.com › python › built-in › max()
Python max() - Find Maximum Value
September 27, 2024 - Here, max() uses a lambda function to compare fruits based on their 'weight' attribute. The output will show apple as it has the highest weight in the list. The max() function in Python provides a straightforward, yet powerful means of finding the maximum value across various data structures.