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
🌐
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 ...
🌐
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 - Instead of comparing raw elements ... length, timestamp, or custom ranking. A lambda expression is commonly used as that key function because it is compact and easy to keep near call site....
🌐
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.
🌐
Learn By Example
learnbyexample.org › python-max-function
Python max() Function - Learn By Example
April 20, 2020 - # Custom class class Student: def __init__(self, name, age): self.name = name self.age = age def __repr__(self): return repr((self.name, self.age)) # a list of custom objects L = [Student('Sam', 35), Student('Tom', 25), Student('Bob', 30)] x = max(L, key=lambda student: student.age) print(x) # Prints ('Sam', 35)
🌐
EyeHunts
tutorial.eyehunts.com › home › python max lambda
Python max lambda
September 6, 2023 - Find the maximum element in a list of custom objects: class Person: def __init__(self, name, age): self.name = name self.age = age # Create a list of Person objects people = [ Person("Alice", 25), Person("Bob", 30), Person("Charlie", 22), Person("David", 35), ] # Find the oldest person in the list using a lambda function as the key oldest_person = max(people, key=lambda person: person.age) print(f"The oldest person is {oldest_person.name} with age {oldest_person.age} years.")
🌐
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
Find elsewhere
🌐
OpenGenus
iq.opengenus.org › python-max-lambda
Python Max Lambda [6 ways]
November 26, 2022 - Similarly, you can use lambda in the key attribute of max() in-built function to support any custom object in Python.
🌐
Hyperskill
hyperskill.org › university › python › max-in-python
Python max() Function — Syntax, key Parameter & Examples
August 10, 2026 - For instance utilizing len as the ... the max() function can execute intricate tasks and manage data proficiently. Lambda functions can be used as the key argument in max() for customized comparisons....
🌐
Finxter
blog.finxter.com › python-max
Python max() — A Simple Illustrated Guide – Be on the Right Side of Change
An optional key function argument allows you to customize the calculation of the maximum by explicitly defining the weight of each value in the iterable that is used as a basis of comparison. Here’s an example: >>> max(1, 2, 3) 3 >>> max(1, 2, 3, key = lambda x: -x) 1 ·
🌐
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 - # lambda function returns second element in the tuple print (min(l1,key=lambda x:x[1])) #Output:(3, 1, 1) print (max(l1,key=lambda x:x[1])) #Output:(8, 5, 3) #Without key function #by default it will take the first element in the tuple. print (min(l1))#Output:(1, 2, 3) print (max(l1))#Output:(8, 5, 3) The operator is a built-in module that contains many operators. itemgetter(n) constructs a function that assumes an iterable object (e.g. list, tuple, set) as input, and fetches the n-th element out of it. As per Python Documentation: operator.itemgetter(item) operator.itemgetter(*items) Return a callable object that fetches item from its operand using the operand’s __getitem__() method.
🌐
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 ... technique. By leveraging the max() and min() functions along with the key parameter, you can efficiently extract values based on custom criteria in various data structures....
🌐
Devcuriosity
devcuriosity.com › manual › details › python-max-function
Python - max() function with examples - DevCuriosity
Here, we provided not one, but two iterables to max(). And without a specific function, max() checked that 100 is bigger than 4, so it returned [100, 4]. my_list_1 = [5, 100, 999] my_list_2 = [100, 4] my_max = max(my_list_1, my_list_2, key=lambda x: sum(x)) print(my_max) # [5, 100, 999] Output: [5, 100, 999] In this example, we also provided two iterables, but we also specified key argument with function sum() to evaluate our lists based on their combined value.
🌐
LabEx
labex.io › tutorials › python-how-to-use-max-function-effectively-464740
How to use max function effectively | LabEx
When exploring max() function, practice with diverse data types and scenarios to enhance your Python skills. ## Handling empty sequences try: max([]) except ValueError as e: print("Cannot find max of empty sequence") ## Complex comparison products = [ {'name': 'Laptop', 'price': 1000}, {'name': 'Phone', 'price': 800}, {'name': 'Tablet', 'price': 500} ] most_expensive = max(products, key=lambda x: x['price']) print(f"Most expensive product: {most_expensive['name']}") ## Sorting complex objects students = [ {'name': 'Alice', 'score': 85, 'age': 22}, {'name': 'Bob', 'score': 85, 'age': 20}, {'nam
🌐
Python Reference
python-reference.readthedocs.io › en › latest › docs › functions › max.html
max — Python Reference (The Right Way) 0.1 documentation
Specifies a one-argument ordering function; must be in keyword form. #TODO · #TODO · When comparing sequences lexical comparison is used. >>> max(1, 2, 3) 3 >>> max('A', 'a', 'b') 'b' >>> max([1, 2], [2, 1], [3, 1]) [3, 1] >>> max(str([1, 2]), str([2, 1]), str([3, 1])) '[3, 1]' >>> max('apple', 'Pear', key=lambda x: x.upper()) 'Pear' >>> max('apple', 'Pear') 'apple' #TODO
🌐
Stack Overflow
stackoverflow.com › questions › 76062232 › python-max-key-and-lambda-with-conditions
list - Python max-key and lambda with conditions - Stack Overflow
You can simplify the lambda function in your code by using the max() function within the lambda function to compare the value with 9 · print(max([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], key=lambda x: x if x < 9 else max([0, x])))
🌐
Honda-event
honda-event.com › wgyr3qj1 › 993e08-python-max-function-key
python max function key
Python max() function: Return the largest item in an iterable or the largest of two or more arguments. If two or more arguments are provided, largest of them will be returned. One such function is the python max function.If you already use it in your program, you … key = lambda k: square[k] The ...
🌐
w3resource
w3resource.com › python-exercises › lambda › python-lambda-exercise-26.php
Python: Find the list with maximum and minimum length using lambda - w3resource
Python Code : # Define a function ... 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 ...