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
Discussions

Can anyone help me with understanding lambda? I have added a sample question with my code not involving lambda and another code involving it
lambda is just a shorthand way to write a function. Anywhere you see lambda you could use def instead. That's it; there's nothing else special about it. Well, except that it makes sophomore programmers feel cool. The short code you showed could be rewritten like this: def magic(k): return sum(ord(c) - 96 for c in k) def high(x): return max(x.split(), key=magic) It's better than your code, but it's not because of lambda. it has potential to shorten my code by a lot Here's an important lesson: short code is not automatically better code. In fact it's often worse. Look at some professional code and even a beginner will often find ways that it could be shorter, but professionals value readability and efficiency over short code. More on reddit.com
🌐 r/learnpython
10
2
July 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
Anonymous / Lambda Function for max
Can you specify you question? More on reddit.com
🌐 r/haskell
9
0
December 1, 2022
Cloudwatch -> Kinesis Firehose -> Lambda Python issue
You are trying to dump the compressed payload, no the decompressed one. More on reddit.com
🌐 r/aws
3
7
January 10, 2018
🌐
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.
🌐
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. ... Let us dive into Python Max Lambda with Python code examples ...
🌐
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.
🌐
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.
🌐
EyeHunts
tutorial.eyehunts.com › home › python max lambda
Python max lambda
September 6, 2023 - data = [1, 3, 5, 2, 4] # Find the ... 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, which means it compares elements in the iterable based on their own values (i.e., it ...
Find elsewhere
🌐
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'
🌐
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 ...
🌐
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 ...
🌐
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( ...
🌐
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
🌐
Programiz
programiz.com › python-programming › methods › built-in › max
Python max()
Let's use the key parameter so that we can find the dictionary's key having the largest value. square = {2: 4, -3: 9, -1: 1, -2: 4} # the largest key · key1 = max(square) print("The largest key:", key1) # 2 # the key whose value is the largest · key2 = max(square, key = lambda k: square[k]) ...
🌐
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....
🌐
Real Python
realpython.com › ref › builtin-functions › max
max() | Python’s Built-in Functions – Real Python
You can use max() with the .items() ... 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 the most expensive ...
🌐
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.
🌐
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 - Using max(): Similarly, the max() function is used to get the dictionary with the largest age, using the same lambda function. Output: We print the results, displaying both the person with the minimum and maximum age. Utilizing lambda functions with min() and max() provides a flexible way to ...
🌐
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.
🌐
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: ...
🌐
Reddit
reddit.com › r/learnpython › can anyone help me with understanding lambda? i have added a sample question with my code not involving lambda and another code involving it
r/learnpython on Reddit: Can anyone help me with understanding lambda? I have added a sample question with my code not involving lambda and another code involving it
July 5, 2024 -

I was practicing coding and I saw some very interesting solutions involving lambda. For example-

The question is-

Given a string of words, you need to find the highest scoring word.

Each letter of a word scores points according to its position in the alphabet: a = 1, b = 2, c = 3 etc.

For example, the score of abad is 8 (1 + 2 + 1 + 4).

You need to return the highest scoring word as a string.

If two words score the same, return the word that appears earliest in the original string.

All letters will be lowercase and all inputs will be valid.

My code-

def high(x):
    dict1 = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10,'k':11,'l':12,'m':13,'n':14,'o':15,'p':16,'q':17,'r':18,'s':19,'t':20,'u':21,'v':22,'w':23,'x':24,'y':25,'z':26}
    split = x.split()
    sum= [0 for i in range(len(split))]
    #split1 = split[0].split("")
    for i in range(len(split)):
        for j in split[i]:
            sum[i]+= dict1[j]
    i = sum.index(max(sum))
    return split[i]                                                                

Meanwhile someone else's code who did it using lambda-

def high(x):
    return max(x.split(), key=lambda k: sum(ord(c) - 96 for c in k))

I am finding lambda a bit confusing but seems it has potential to shorten my code by a lot