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
🌐
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.
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
Discussions

Why does min() in Python return the key when a lambda is used on dictionaries? - Stack Overflow
I tested this on Python 3.6.0, and it returns 'FB'. My understanding is that every key from the prices dictionary is sent to the lambda as parameter k and then the lambda returns the value associated with key k in the prices dictionary. So after iterating through all the keys, a list of values is returned which is used as an argument to the min ... More on stackoverflow.com
🌐 stackoverflow.com
Allow `min()` and `max()` to return both the key and value - Ideas - Discussions on Python.org
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. This leads to redundant code where users have to ... More on discuss.python.org
🌐 discuss.python.org
0
September 5, 2024
[Python] Question! I am having trouble with min/max
I do't understand what key or lambda means, even after reading about them. And then the x: x[1] makes it extra confusing. Can anyone help me? First lambda: lambda is just a way to define a function inline. min([[1, 2], [3, 4], [9, 0]], key=lambda x: x[1]) is equivalent to: def f(x): return x[1] min([[1, 2], [3, 4], [9, 0]], key=f) The idea of the key argument (often used for various comparison functions like min, max or sort) is that you can pass in a function that will transform the data before comparing. So, if your key is lambda x: x[1] what you're really saying is: "take the second element of each list and compare those, then return the list that had the largest value." In the case above, comparing [1, 2], [3, 4], and [9, 0], we compare 2, 4, and 0. 4 is largest so we want to return [3, 4] More on reddit.com
🌐 r/learnpython
19
7
June 21, 2015
python - What is the correct use of "key" in the min() function? - Stack Overflow
I have a question about the min() function in Python. I am confused about the use of the "key" option in min(). Could someone explain how key works in min(), especially in relation to a lambda function? More on stackoverflow.com
🌐 stackoverflow.com
🌐
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.
🌐
Programiz
programiz.com › python-programming › methods › built-in › min
Python min()
In the second min() function, we have passed a lambda function to the key parameter.
🌐
OpenGenus
iq.opengenus.org › python-min-lambda
Python Min Lambda [5 ways]
November 26, 2022 - If you want the min() function to consider the elements are number, one can use lambda in key attribute of min() to support this custom functionality. The following Python code snippet demonstrates the approach:
🌐
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
🌐
Medium
medium.com › @zzysjtu › python-min-function-a-deep-dive-f72cbd771872
Python min() Function: A Deep Dive | by Derek | Medium
August 13, 2023 - If the key argument is not specified, the min() function will compare the values in the iterable using their natural order.
🌐
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 …
🌐
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)
🌐
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.
🌐
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.
🌐
Bacancy Technology
bacancytechnology.com › qanda › python › use-lambda-for-sorting-in-python
How to Use Lambda for Sorting in Python: A Quick Guide
January 20, 2025 - Explanation: key=lambda x: x.modified tells Python to use the modified attribute of each element in the list a as the sorting criterion.
🌐
Reddit
reddit.com › r/learnpython › [python] question! i am having trouble with min/max
r/learnpython on Reddit: [Python] Question! I am having trouble with min/max
June 21, 2015 -

I am supposed to write my own min/max functions. They should be able to deal with ints, strings, lists, and whatnot. I'm having trouble. Firstly, if my input is a list, how do I ignore the list and simply look at the numbers/letters inside? My other, more confusing question is:

min([[1, 2], [3, 4], [9, 0]], key=lambda x: x[1]) == [9, 0], "lambda key"

It says the output should be [9, 0] if I input:

min([[1, 2], [3, 4], [9, 0]], key=lambda x: x[1])

I do't understand what key or lambda means, even after reading about them. And then the x: x[1] makes it extra confusing. Can anyone help me?

Top answer
1 of 4
5
I do't understand what key or lambda means, even after reading about them. And then the x: x[1] makes it extra confusing. Can anyone help me? First lambda: lambda is just a way to define a function inline. min([[1, 2], [3, 4], [9, 0]], key=lambda x: x[1]) is equivalent to: def f(x): return x[1] min([[1, 2], [3, 4], [9, 0]], key=f) The idea of the key argument (often used for various comparison functions like min, max or sort) is that you can pass in a function that will transform the data before comparing. So, if your key is lambda x: x[1] what you're really saying is: "take the second element of each list and compare those, then return the list that had the largest value." In the case above, comparing [1, 2], [3, 4], and [9, 0], we compare 2, 4, and 0. 4 is largest so we want to return [3, 4]
2 of 4
3
Okay, when you use min() on anything else but integers or floats (things that have a defined natural order), you need to tell min() what to compare the items with. So, for your example, we have this list: [[1, 2], [3, 4], [9, 0]] And we want to find which of these three lists has the lowest second element. For that, we'll use the key parameter. That allows us to specify a function that will be called on each of the input items to allow us to sort them. A lambda function is just a way to quickly make a function that we don't plan to use anywhere else. We could rewrite this with a normal function like this: def return_first(x): return x[1] min([[1, 2], [3, 4], [9, 0]], key=return_first) And the program still works as expected! So, all that this key=lambda x: x[1] is saying is: when you get an item x, return the first (not 0th) element from the item x, and perform the comparison on that, rather than the item as a whole. Does that make sense?
Top answer
1 of 4
2

The code is using the min builtin function, but with a key parameter. Thus, it does not return the actual minimum element of the list, but the element for which that key function is minimal, i.e. it behaves more like "arg-min" than actually "min".

In the key function (defined as a lambda expression), abs is just the absolute difference, in this case between the parameter x (a number from the list) and 5.

That line is somewhat equivalent to, but much shorter and more readable than, this loop:

a = [1,3,4,7,8,9,12,13,14]
b = min_k = None
for x in a:
    k = abs(x-5)
    if min_k is None or k < min_k:
        b, min_k = x, k
2 of 4
1

Explanation

min(iterable, key) returns the smallest item in the iterable with respect to the key. So it iterates over the iterable, each time evaluates the key(x) for an element x, and then returns the element for which key(x) was the smallest.

Since key=lambda x=abs(x-5), we thus evaluate the absolute difference between 5, so if x=3, then abs(x-5) is 2, etc. So this will result in the number that is the closest to 5.

Making this an O(log n) algorithm

Given the list is ordered, you can find this in logarithmic time with:

from bisect import bisect_left

def closest(ordered_list, x):
    idx = bisect_left(ordered_list, x)
    return min(ordered_list[max(idx-1,0):idx+1], key=lambda y: abs(y-x))

For example:

>>> closest(a, -1)
1
>>> closest(a, 0)
1
>>> closest(a, 1)
1
>>> closest(a, 2)
1
>>> closest(a, 3)
3
>>> closest(a, 4)
4
>>> closest(a, 5)
4
>>> closest(a, 6)
7
>>> closest(a, 11)
12
>>> closest(a, 15)
14
🌐
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 ......
🌐
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 find a list with maximum and minimum length using lambda. ... # Define a function 'max_length_list' that takes a list of lists 'input_list' as input def max_length_list(input_list): # Calculate the maximum length of the sublists in 'input_list' max_length = max(len(x) for x in input_list) # Find the sublist with 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 maximum length return (max_length, max_list) # Define a function 'min_len