Python Built-in Methods – Python max() Function

Hits: 3

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)

Parameter Condition Description
val1,val2,val3… Required Two or more values to compare
key Optional A function to specify the comparison criteria.
Default value is None.

– OR –

max(iterable,key,default)

Parameter Condition Description
iterable Required Any iterable, with one or more items to compare
key Optional A function to specify the comparison criteria.
Default value is None.
default Optional A 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

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)

 

Python Example for Beginners

Two Machine Learning Fields

There are two sides to machine learning:

  • Practical Machine Learning:This is about querying databases, cleaning data, writing scripts to transform data and gluing algorithm and libraries together and writing custom code to squeeze reliable answers from data to satisfy difficult and ill defined questions. It’s the mess of reality.
  • Theoretical Machine Learning: This is about math and abstraction and idealized scenarios and limits and beauty and informing what is possible. It is a whole lot neater and cleaner and removed from the mess of reality.

Data Science Resources: Data Science Recipes and Applied Machine Learning Recipes

Introduction to Applied Machine Learning & Data Science for Beginners, Business Analysts, Students, Researchers and Freelancers with Python & R Codes @ Western Australian Center for Applied Machine Learning & Data Science (WACAMLDS) !!!

Latest end-to-end Learn by Coding Recipes in Project-Based Learning:

Applied Statistics with R for Beginners and Business Professionals

Data Science and Machine Learning Projects in Python: Tabular Data Analytics

Data Science and Machine Learning Projects in R: Tabular Data Analytics

Python Machine Learning & Data Science Recipes: Learn by Coding

R Machine Learning & Data Science Recipes: Learn by Coding

Comparing Different Machine Learning Algorithms in Python for Classification (FREE)

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.