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
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 - 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.
🌐
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.
🌐
EyeHunts
tutorial.eyehunts.com › home › python max lambda
Python max lambda
September 6, 2023 - data = [1, 3, 5, 2, 4] # Find the maximum element in the list using a lambda function as the key max_value = max(data, key=lambda x: x) print(max_value) # Output: 5 · In this example, the lambda function lambda x: x is used as the key function, ...
🌐
Python Basics
python-basics-tutorial.readthedocs.io › en › latest › functions › lambda.html
Lambda functions - Python Basics
However, there is no global variable to store the values of the lambda function: 1>>> count = ["1", "123", "1000"] 2>>> max(count) 3'123' 4>>> max(count, key=lambda val: int(val)) 5'1000'
🌐
GeeksforGeeks
geeksforgeeks.org › python-program-maximum-of-three-number-using-lambda
Python Program Maximum of Three Number using Lambda - GeeksforGeeks
February 9, 2024 - 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 ...
Find elsewhere
🌐
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 - Finding maximum and minimum values in a dataset is a common task in programming, especially when dealing with lists. In Python, lambda expressions provide a concise way to perform this task, allowing you to write cleaner and more efficient code.
🌐
Hyperskill
hyperskill.org › university › python › max-in-python
Python max() Function — Syntax, key Parameter & Examples
August 10, 2026 - For instance utilizing len as the function assists in identifying the longest string, within a list. By collaborating with built in functions the max() function can execute intricate tasks and manage data proficiently. Lambda functions can be used as the key argument in max() for customized ...
🌐
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.
🌐
Programiz
programiz.com › python-programming › methods › built-in › max
Python max()
# find max among the arguments result = max(4, -5, 23, 5) print("The maximum number is:", result) ... If you need to find the smallest item, you can use the Python 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 ... : 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( ...
🌐
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 ...
🌐
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 - In production analytics code, make ranking criteria explicit in variable names. For example, define score_key = lambda r: (r["priority"], r["updated_at"]) and pass that variable to max.
🌐
Real Python
realpython.com › ref › builtin-functions › max
max() | Python’s Built-in Functions – Real Python
Language: 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) This example demonstrates how max() can help you identify ...
🌐
Devcuriosity
devcuriosity.com › manual › details › python-max-function
Python - max() function with examples - DevCuriosity
So in this example, we told max() to simply check for the longest word in a list. my_list_1 = [5, 100, 999] my_list_2 = [100, 4] my_max = max(my_list_1, my_list_2) print(my_max) # [100, 4] Output: [100, 4] Here, we provided not one, but two iterables to max(). And without a specific function, ...
🌐
Markmeretzky
markmeretzky.com › python › list › max.html
max with lambda
""" import sys chronologicalOrder = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ] months = ["February", "August", "May"] try: m = max(months, key = lambda month: chronologicalOrder.index(month)) except ValueError: print(f"Sorry, your list contains a string that is not a month.", file = sys.stderr) sys.exit(1) print(f"m = {m}") sys.exit(0)