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
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-min-function
Python min() Function - GeeksforGeeks
July 15, 2025 - Example 2: In this example, min() uses key=lambda x: x[1] to find the tuple with the smallest second element.
People also ask

How does the key argument work in Python min()?
key is a function applied to every item to decide what to compare, while min still returns the original item. min(products, key=lambda p: p['price']) returns the whole cheapest product dict, not just the price. It is the same pattern as sorted's key, and for a single minimum it is faster and clearer than sorting and taking the first element.
🌐
runxbuild.com
runxbuild.com › home › blog › python min(): the key argument is the part worth learning
Python min(): The key Argument Is the Part Worth Learning
How do I stop min() from raising ValueError on an empty list?
Pass the default argument: min(items, key=..., default=None). When the iterable is empty, min returns the default instead of raising. It is keyword-only and only valid when you pass a single iterable. Use it any time the iterable is the result of a filter that could legitimately be empty.
🌐
runxbuild.com
runxbuild.com › home › blog › python min(): the key argument is the part worth learning
Python min(): The key Argument Is the Part Worth Learning
Is min() faster than sorting to find the smallest value?
Yes. min() makes a single O(n) pass, while sorted(items)[0] is O(n log n) and allocates a fully sorted list you then discard. For one minimum use min; for the k smallest use heapq.nsmallest; only sort when you actually need the whole sequence ordered.
🌐
runxbuild.com
runxbuild.com › home › blog › python min(): the key argument is the part worth learning
Python min(): The key Argument Is the Part Worth Learning
🌐
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.
🌐
Programiz
programiz.com › python-programming › methods › built-in › min
Python min()
key2 = min(square, key = lambda k: square[k]) print("The key with the smallest value:", key2) # -1 # getting the smallest value print("The smallest value:", square[key2]) # 1
🌐
Medium
medium.com › @zzysjtu › python-min-function-a-deep-dive-f72cbd771872
Python min() Function: A Deep Dive | by Derek | Medium
August 13, 2023 - The Python min() function is a built-in function that returns the smallest value in an iterable. It can be used with any iterable data type, such as lists, tuples, sets, and strings.
🌐
OpenGenus
iq.opengenus.org › python-min-lambda
Python Min Lambda [5 ways]
November 26, 2022 - Python comes with it own min() built-in function which can be used to find the minimum element in a list. In some cases, you need to find the minimum in a custom way. In this case, lambda is used to set the key attribute of min() function.
🌐
Educative
educative.io › answers › min-max-with-key-function
Min-Max with Key function
key2 = min(square, key = lambda k: square[k]) print("The key with the smallest value:", key2) # getting the smallest value · print("The smallest value:", square[key2]) Run · # Example of max() on Dictionaries · square = {2: 4, -3: 9, -1: ...
Find elsewhere
🌐
RunxBuild
runxbuild.com › home › blog › python min(): the key argument is the part worth learning
Python min(): The key Argument Is the Part Worth Learning
July 21, 2026 - key is a function applied to every item to decide what to compare, while min still returns the original item. min(products, key=lambda p: p[‘price’]) returns the whole cheapest product dict, not just the price.
🌐
Mimo
mimo.org › glossary › python › min
Python min(): Syntax, Usage, and Examples
Python works with any iterable, including sets and tuples. Suppose you have a list of dictionaries representing books: ... books = [ {"title": "Book A", "pages": 300}, {"title": "Book B", "pages": 150}, {"title": "Book C", "pages": 500}, ] shortest = min(books, key=lambda x: x["pages"]) print(shortest["title"]) # Output: Book B
🌐
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 - How to Use Key Function in Max() and Min() in Python Learn to use key parameters in max( ) and min( ). Key Function in Max() and Min() in Python A key function is a callable that returns a value used …
🌐
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
Write a Python program to find the maximum and minimum values in a given list of tuples using the lambda function. ... # 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 f
🌐
Jszafran
jszafran.dev › posts › python_min_max_and_key_parameter
TIL: Python's min and max functions have a key argument. • Jakub Szafran personal blog
July 6, 2024 - def find_event_with_min_timestamp_3(events: Sequence[SomeEvent]) -> SomeEvent: return min(events, key=lambda x: x.timestamp) What if min receives an empty iterable? ValueError is raised.
🌐
IONOS
ionos.com › digital guide › websites › web development › lambda functions in python
How to use lambda functions in Python - IONOS
September 17, 2023 - The key function is used locally and once only. It’s not necessary to define an extra named function for it. Lambdas are the correct way to create key functions. Let’s take a look at two more examples. Like sorted(), the built-in Python functions min() and max() take an optional key function.
🌐
Real Python
realpython.com › ref › builtin-functions › min
min() | Python’s Built-in Functions – Real Python
>>> prices = { ... "banana": 1.20, ... "pineapple": 0.89, ... "apple": 1.57, ... "grape": 2.45, ... } >>> min(prices.items(), key=lambda item: item[1]) ('pineapple', 0.89)
🌐
Note.nkmk.me
note.nkmk.me › home › python
How to Use the key Argument in Python (sorted, max, etc.) | note.nkmk.me
August 13, 2023 - In Python, you can specify a function or callable for the key argument in the built-in functions such as sorted(), max(), min(), etc. Sorting HOW TO - Key Functions — Python 3.11.4 documentation ... Speed comparison between lambda expression and operator.itemgetter().
🌐
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 or object are needed.
🌐
GeeksforGeeks
geeksforgeeks.org › use-of-min-and-max-in-python
Use of min() and max() in Python - GeeksforGeeks
June 6, 2021 - Here you notice that output comes ... any extra parameters. however, it has an optional parameters: key - function that serves as a key for the min/max ......