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
๐ŸŒ
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 - How do I find the maximum value in a list of numbers using lambda? You can use the max() function with a lambda expression as the key to determine the maximum value based on specific criteria.
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
๐ŸŒ
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.
๐ŸŒ
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 - Write a Python program to find the maximum value in a given heterogeneous list using lambda. ... # Define a function 'max_val' that takes a list 'list_val' as input def max_val(list_val): # Find the maximum value in 'list_val' based on two criteria: # 1. First, sort by whether the element is an integer or not (True for integers, False for non-integers) # 2.
๐ŸŒ
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 - # 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)
๐ŸŒ
PyQuestHub
pyquesthub.com โ€บ harnessing-the-power-of-lambda-with-min-and-max-in-python
Using Lambda Functions with min() and max() in Python
November 21, 2024 - Utilizing lambda functions with min() and max() provides a flexible way to filter and define your criteria when searching for minimum or maximum values in Python.
Find elsewhere
๐ŸŒ
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.
๐ŸŒ
Vultr Docs
docs.vultr.com โ€บ python โ€บ built-in โ€บ max()
Python max() - Find Maximum Value
September 27, 2024 - Learn that max() allows for a custom key function to specify the criteria for comparison. Use a key function to assess elements based on a specific attribute or predefined logic. Apply max() with the key function to identify the desired maximum element. ... fruits = [{'name': 'apple', 'weight': ...
๐ŸŒ
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 identify the sublist with the highest average value and the one with the lowest average using lambda. Write a Python program to determine the list with the maximum number of unique elements and the one with the minimum using lambda.
๐ŸŒ
Real Python
realpython.com โ€บ ref โ€บ builtin-functions โ€บ max
max() | Pythonโ€™s Built-in Functions โ€“ Real Python
The built-in max() function allows you to find the largest values in an iterable or among multiple arguments.
๐ŸŒ
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 ...
๐ŸŒ
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.
๐ŸŒ
Learn Coding Fast
learncodingfast.com โ€บ home โ€บ max() function in python
max() function in Python | Learn Coding Fast
September 8, 2020 - If you want to define the largest item using a different criteria, you can pass an additional argument โ€“ key โ€“ to the function. key can be assigned a named function or a lambda function.
๐ŸŒ
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 - max(..., key=...) is the idiomatic way to select the best element from complex data in Python, and lambda provides a concise ranking function at call site. Add tuple keys for tie-breaking, default for empty inputs, and prioritize readability ...
๐ŸŒ
Devcuriosity
devcuriosity.com โ€บ manual โ€บ details โ€บ python-max-function
Python - max() function with examples - DevCuriosity
First Occurrence Preference: If multiple items are equal by key criteria, max() returns the first encountered.
Top answer
1 of 4
3

There is really nothing wrong with the way you were going about this. You just needed to incorporate your lambda into the rest of your code in the right way:

myList = [1,2,3,10,4,5,6,7,8,9]

def maxVal(list_a, compare_function):
    max = -sys.maxsize - 1  # strange but true...this seems to be the canonical way to get the smallest 32 bit `int`
    for i in list_a:
        if compare_function(i, max):
            max = i
    return max

my_compare_function = lambda x,y: max(x, y)

print(maxVal(myList, my_compare_function))

Result:

10

I did have to change at what level return max was being called. I don't know if this was a logic error, or just a transcription error when you put your code into a S.O. question. Also note that I moved the 10 to a different place in your input data to make sure it didn't have to be at the end to be found to be the largest value.

If you want a "cooler" and more modern answer, reduce is really designed to do just what you want. Here's a simple solution.

import functools

myList = [1,2,3,10,4,5,6,7,8,9]
r =  functools.reduce(lambda v1, v2: max(v1, v2), myList)
print(r)

Result:

10

Also note that 'max' itself is a function that takes two parameters, so you could use it directly to get to something very simple...not that this works in your case where your assignment is to use a lambda:

myList = [1,2,3,10,4,5,6,7,8,9]
r =  functools.reduce(max, myList)
print(r)

These functional equivalents to writing loops are all the rage, and for good reason. When combined with processing data as streams, it's a super powerful idea. And as it becomes more popular, I think it will be thought to be more readable. As an old timer, I'm just getting on board with all of this functional/streams programming...more in Java than Python, but still. It's a powerful set of tools that would be to your benefit to really understand well.

2 of 4
1

You can define a function that takes a list as the first parameter and optionally a current maximum as the second parameter, and recursively calls itself with the first item in the list as the second argument if it's bigger than the current maximum or if the current maximum is None, and the rest of the list as the first argument, until the rest of the list is empty, at which point returns the current maximum:

maxVal = lambda lst, m=None: maxVal(lst[1:], m if m is not None and lst[0] < m else lst[0]) if lst else m

so that:

from random import shuffle
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
shuffle(myList)
print(maxVal(myList))

outputs: 10

๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 76062232 โ€บ python-max-key-and-lambda-with-conditions
list - Python max-key and lambda with conditions - Stack Overflow
print(max([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], key=lambda x: x if x<9 else 0)) This code-snip does indeed work, but i wonder whether there is a way to remove the else-part in the lambda function itself, as this seems to be a necessary "parameter". I am very well aware that i could just use a list comprehension like [i for i in arr if i<9], but i am looking for solutions to this specific function. I am using Python 3.10.6.