Python max() Function

Returns the largest item

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)

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 –

max(iterable,key,default)

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.

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

If the values are strings, the string with the highest value in alphabetical order is returned.

x = max('red', 'green', 'blue')
print(x)
# Prints 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.

L = [300, 500, 100, 400, 200]
x = max(L)
print(x)
# Prints 500

If the iterable is empty, a ValueError is raised.

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

To avoid such exception, add default parameter. The default parameter specifies a value to return if the provided iterable is empty.

# Specify default value '0'
L = []
x = max(L, default='0')
print(x)
# Prints 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.

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

Find Maximum with Custom Function

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

# 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)
# Prints ('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.

# 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)

Find Maximum of Custom Objects

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

# 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)
# Prints ('Sam', 35)