Python

Python max() Function

Returns the largest item

Basic Example

Example: Return the largest number

x = max(10, 20, 30)
print(x)    # 30

Usage

The max() function can find

  • the largest of two or more values (such as numbers, strings etc.)
  • the largest item in an iterable (such as list, tuple etc.)

With optional key parameter, you can specify custom comparison criteria to find maximum value.

Syntax

max(val1,val2,val3… ,key)

– OR –

max(iterable,key,default)

Parameters

Python max() function parameters
ParameterConditionDescription
val1,val2,val3…RequiredTwo or more values to compare
keyOptionalA function to specify the comparison criteria.
Default value is None.

– OR –

Python max() function parameters
ParameterConditionDescription
iterableRequiredAny iterable, with one or more items to compare
keyOptionalA function to specify the comparison criteria.
Default value is None.
defaultOptionalA value to return if the iterable is empty.
Default value is False.

Find Maximum of Two or More Values

If you specify two or more values, the largest value is returned.

Example: Return the largest number

x = max(10, 20, 30)
print(x)    # 30

Example: Return the string with the highest value, ordered alphabetically

x = max('red', 'green', 'blue')
print(x)    # red

You have to specify minimum two values to compare. Otherwise, TypeError exception is raised.

Find Maximum in an Iterable

If you specify an Iterable (such as list, tuple, set etc.), the largest item in that iterable is returned.

Example: Return a list item with the highest value, ordered alphabetically

L = ['red', 'green', 'blue']
x = max(L)
print(x)    # red

If the iterable is empty, a ValueError is raised.

Example:

# ValueError: max() arg is an empty sequence
L = []
x = max(L)
print(x)

To avoid such exception, add default parameter.

The default parameter specifies a value to return if the provided iterable is empty.

Example: Specify default value ‘0’ to return if the iterable is empty

L = []
x = max(L, default='0')
print(x)	# 0

Find Maximum with Built-in Function

With optional key parameter, you can specify custom comparison criteria to find maximum value.

A key parameter specifies a function to be executed on each iterable’s item before making comparisons.

For example, with a list of strings, specifying key=len (the built-in len() function) finds longest string.

Example: Find longest string in a list

L = ['red', 'green', 'blue']
x = max(L, key=len)
print(x)    # green

Find Maximum with Custom Function

You can also pass in your own custom function as the key function.

Example: Find out who is the oldest student

def myFunc(e):
  return e[1]	# return age

L = [('Sam', 35),
    ('Tom', 25),
    ('Bob', 30)]

x = max(L, key=myFunc)
print(x)	# ('Sam', 35)

A key function takes a single argument and returns a key to use for comparison.

Find Maximum with lambda

A key function may also be created with the lambda expression.

It allows us to in-line function definition.

Example: Find out who is the oldest student

L = [('Sam', 35),
    ('Tom', 25),
    ('Bob', 30)]

x = max(L, key=lambda student: student[1])
print(x)	# ('Sam', 35)

Find Maximum of Custom Objects

Let’s create a list of students (custom object) and find out who is the oldest student.

Example:

# Custom class
class Student:
	def __init__(self, name, age):
		self.name = name
		self.age = age
	def __repr__(self):
		return repr((self.name, self.age))

# a list of custom objects
L = [Student('Sam', 35),
	Student('Tom', 25),
	Student('Bob', 30)]


x = max(L, key=lambda student: student.age)

print(x)    # ('Sam', 35)