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

How to retrieve well formatted JSON from AWS Lambda using Python - Stack Overflow
I have a function in AWS Lambda that connects to the Twitter API and returns the tweets which match a specific search query I provided via the event. A simplified version of the function is below. ... More on stackoverflow.com
🌐 stackoverflow.com
Malformed JSON in AWS Lambda using Python.
Probably Postman believes that the output is plain text. Try to set "Content-Type" header to "application/json". More on reddit.com
🌐 r/learnpython
2
1
September 11, 2023
Python Lambda event and responses questions

See here for your python-specific questions: https://docs.aws.amazon.com/lambda/latest/dg/python-programming-model-handler-types.html

A lambda can return anything, or nothing at all. However, if you want to call via HTTP, you're gonna have to put an API Gateway or ALB in front of it, which uses the status code, headers, and body to generate a http response.

More on reddit.com
🌐 r/aws
3
8
May 27, 2019
How to Output Lambda Logs to CloudWatch in JSON format in Python?
There’s an implementation on stack overflow https://stackoverflow.com/questions/48170682/can-structured-logging-be-done-with-pythons-standard-library - I haven’t tried it but it looks sensible. More on reddit.com
🌐 r/aws
1
2
March 15, 2023
🌐
Stack Overflow
stackoverflow.com › questions › 74393116 › python-get-data-json-value-max
python get data json value max - Stack Overflow
Copyfrom json import load with open("file.json") as f: dictionary_max = max(load(f), key=lambda x: x["value"]) result = { "T3_Periodo": dictionary_max["T3_Periodo"], "Anyo": dictionary_max["Anyo"], "value": dictionary_max["value"], } print(result) output: {'T3_Periodo': 'M07', 'Anyo': 2022, 'value': 10.8} Share ·
🌐
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....
🌐
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.
🌐
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 ...
🌐
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.
Find elsewhere
🌐
Real Python
realpython.com › ref › builtin-functions › max
max() | Python’s Built-in Functions – Real Python
>>> prices = { ... "banana": 1.20, ... "pineapple": 0.89, ... "apple": 1.57, ... "grape": 2.45, ... } >>> max(prices.items(), key=lambda item: item[1]) ('grape', 2.45)
🌐
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 in Python to find maximum and minimum values is a straightforward yet powerful 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.
🌐
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.
🌐
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' 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_length_list' that takes a list of lists 'input_list' as input def min_length_list(input_lis
🌐
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.
🌐
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.
🌐
W3Schools
w3schools.com › python › ref_func_max.asp
Python max() Function
Python Examples Python Compiler ... Interview Q&A Python Training ... The max() function returns the item with the highest value, or the item with the highest value in an iterable....
🌐
Programiz
programiz.com › python-programming › methods › built-in › max
Python max()
max() returns the largest element from an iterable. ... If the items in an iterable are strings, the largest item (ordered alphabetically) is returned. languages = ["Python", "C Programming", "Java", "JavaScript"]
🌐
Reddit
reddit.com › r/learnpython › malformed json in aws lambda using python.
r/learnpython on Reddit: Malformed JSON in AWS Lambda using Python.
September 11, 2023 -

Hello LeanPython Sub-reddit!

I come to you because I have a problem formatting JSON in AWS Lambda.

I would like to tell you a little more, what happens is that I am developing an API in AWS Lambda, I created the database in PostgreSQL, and I am using Python to perform the queries, what happens is that I had a datatimes management error, because these values could not be formatted in a JSON, so I decided to make an encoder in a class which is responsible for carrying out this process of formatting it to JSON, but what happens is that it generates a JSON which is very poorly readable, in addition to being a headache when trying to manipulate it in the Frontend, below I will show you what I did and I would like to consult with you about a possible solution to this problem, please.

Below you will find the encoder class I was talking about:

class DateTimeEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, datetime):
            return o.isoformat()

        return json.JSONEncoder.default(self, o)

In the following function I am using json.dumps to format the output of the database query into JSON, in conjunction with the encoder:

def lambda_handler(event, context):
    cur = conn.cursor(cursor_factory=RealDictCursor)
    cur.execute("SELECT * FROM users")
    results = cur.fetchall()
    return  json.dumps(results, cls=DateTimeEncoder)

When deploying this in AWS in a Lambda, and when making the HTTP request through Postman, it generates the following poorly formatted output:

"[{\"id_usuario\": 2, \"cc\": \"123456789\", \"telefono\": \"987654321\", \"nombre\": \"John\", \"apellido\": \"Doe\", \"fecha_registro\": \"2023-07-03T02:34:38.452359\"}, {\"id_usuario\": 3, \"cc\": \"1013655876\", \"telefono\": \"2085686\", \"nombre\": \"Jane\", \"apellido\": \"Doe\", \"fecha_registro\": \"2023-07-03T20:08:42.603593\"}]"

What I want is for the above JSON to look like this:

[
  {
    "id_usuario": 2,
    "cc": "123456789",
    "telefono": "987654321",
    "nombre": "John",
    "apellido": "Doe",
    "fecha_registro": "2023-07-03T02:34:38.452359"
  },
  {
    "id_usuario": 3,
    "cc": "1013655876",
    "telefono": "2085686",
    "nombre": "Jane",
    "apellido": "Doe",
    "fecha_registro": "2023-07-03T20:08:42.603593"
  }
]

If you ask me, I have made other queries that have not had to use the json.dumps and it has generated the JSON with the correct format, however, when I implement the json.dumps in conjunction with the encoder, it generates that output which is difficult to read, I sincerely hope you can help me because I don't know what else to do.

🌐
LabEx
labex.io › tutorials › python-how-to-use-a-custom-key-in-the-max-function-in-python-398075
How to use a custom key in the max function in Python | LabEx
In this example, the custom key function lambda person: person["score"] extracts the "score" value from each dictionary in the people list, and the max() function uses these scores to determine the person with the highest score. By leveraging custom keys, you can tailor the max() function to meet your specific needs and extract the largest item based on your desired criteria. The ability to use custom keys with the max() function in Python opens up a wide range of practical applications.
🌐
PyPI
pypi.org › project › lambdaJSON
lambdaJSON · PyPI
Serialize python standard types (function, tuple, class, memoryview, set, frozenset, exceptions, complex, range, bytes, bytearray, dict with number keys, byte keys or tuple keys, and etc) with json. lambdaJSON lets you serialize python standard library objects with json.
      » pip install lambdaJSON
    
Published: Jul 23, 2015
Version: 4.3
🌐
Finxter
blog.finxter.com › python-max
Python max() — A Simple Illustrated Guide – Be on the Right Side of Change
>>> max(1, 2, 3) 3 >>> max(1, 2, 3, key = lambda x: -x) 1 · Syntax: max(iterable, *[, key, default]) max(arg1, arg2, *args[, key]) The max() function returns the maximum among at least two arguments. >>> max(1, 2, 3) 3 · The max() function returns the maximum of the provided arguments.