Skip to content

Python max lambda

  • by

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.

Here’s a brief explanation of how it works:

max_value = max(iterable, key=lambda x: custom_criteria)
  • iterable: This is the iterable (e.g., a list, tuple, or other sequence) in which you want to find the maximum value.
  • key: This is an optional argument that allows you to specify a function (usually a lambda function) that calculates a value for each element in the iterable. The max() function will then find the element with the maximum calculated value according to this key function.
  • x: This is a placeholder representing an element from the iterable.
  • custom_criteria: This is the lambda function or custom function you provide that determines the criterion for finding the maximum element. It takes an element from the iterable (x) and returns a value based on which the maximum is determined.

Python max lambda example

Here’s an example of how to use max() with a lambda function:

data = [1, 3, 5, 2, 4]

# Find the maximum element in the list using a lambda function as 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 finds the maximum numeric value in the list).

Find the maximum element in a list of custom objects:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

# Create a list of Person objects
people = [
    Person("Alice", 25),
    Person("Bob", 30),
    Person("Charlie", 22),
    Person("David", 35),
]

# Find the oldest person in the list using a lambda function as the key
oldest_person = max(people, key=lambda person: person.age)

print(f"The oldest person is {oldest_person.name} with age {oldest_person.age} years.")  

Find the maximum length string in a list of strings:

strings = ["apple", "banana", "cherry", "date"]

# Find the string with the maximum length using a lambda function as the key
max_length_string = max(strings, key=lambda x: len(x))

print(max_length_string)

Output:

Python max lambda example

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading