Learn the max() Function in Python with Examples

Learn the max() Function in Python with Examples

5 mins read691 Views 16 Comments
Updated on Aug 16, 2024 14:41 IST

This article includes introduction to max() Function in Python and Examples of Using the max() Function in Python.

2023_04_MicrosoftTeams-image-19.jpg

The max() function is an in-built technique to determine the largest value within a list. Alternatively, when given a list of strings, it returns the string with the greatest lexicographic value.

In this article, we will discuss the max() function and understand its use with the help of examples. We will be covering the following sections:

Introduction max() Function in Python

Python’s max() function is a built-in function that returns the highest or largest element in an iterable or given input. 

The function can take one or more arguments, including a list, tuple, set, or individual values. The returned value is the maximum element in the input. If the input includes elements of different data types, the function will raise a TypeError. Additionally, if the input is empty and a default value is not provided, the function will raise a ValueError

Syntax of max()

The syntax of the max() function in Python is given as follows:


 
max(iterable, *iterables[, key, default])
Copy code

Parameters of max()

Here,

·     iterable: This is the required iterable or sequence, such as a list, tuple, set, or string, from which the minimum value is to be retrieved.

·     *iterables: This optional parameter allows multiple iterables to be passed as arguments.

·     key: This parameter is optional and takes a function as its argument. This function is used to customize the comparison between elements of the iterable.

·     default: This parameter is also optional and is used to specify a default value if the iterable is empty.

Return Value of max()

If the max() function is used without an iterable, it will return the highest object among the parameters that are passed to it. On the other hand, if the max() function is used with an iterable, it will return the most significant element in the iterable.

Exceptions of max()

Two types of exceptions can occur when using the max() function in Python:

  • If the iterable is empty and no default value is provided in the parameter, the max() function will raise a ValueError.
  • If the parameter includes values of different data types, the max() function will raise a TypeError.
Find the Second Occurrence of a Substring in Python String
How to use pass statement in Python
Introduction to Recursion Functions in Python
Recommended online courses

Best-suited Python courses for you

Learn Python with these high-rated online courses

– / –
40 hours
– / –
5 days
– / –
3 days
3 K
3 weeks
– / –
4 days
– / –
20 hours
– / –
2 months
Free
6 weeks

Examples of Using the max() Function in Python

Example 1: Using max() with Python list


 
numbers = [2, 5, 3, 7, 1]
maximum_number = max(numbers)
print(maximum_number)
Copy code

Output:

7

Explanation: In this example, a list of numbers is created and assigned to the variable numbers. The max() function is then used to find the highest number in the list, which is assigned to the variable maximum_number. Finally, the highest number is printed on the console.

You can also explore – Python Projects for Beginners

Example 2: Using max() with Python Tuple


 
values = (3.5, 2.8, 4.2, 1.6, 5.1)
max_value = max(values)
print(max_value)
Copy code

Output:

5.1

In this example, we have a tuple of floating-point numbers called values. We pass this tuple as an argument to the max() function, which returns the largest value in the tuple, i.e., 5.1. We store this value in the max_value variable and print it.

Example 3: Using max() with a Custom Key Function


 
students = [("Alice", 20), ("Bob", 18), ("Charlie", 21)]
oldest_student = max(students, key=lambda x: x[1])
print(oldest_student[0])
Copy code

Output:

Charlie

In this example, a list of tuples containing students’ names and ages is created and assigned to the variable students. The max() function is then used to find the tuple with the highest age by specifying a custom key function that returns the second item in each tuple (the age). The tuple with the highest age is assigned to the variable oldest_student, and the name of the oldest student is printed on the console.

Example 4: Using max() with a Default Value


 
empty_list = []
default_value = "No values found"
max_value = max(empty_list, default=default_value)
print(max_value)
Copy code

Output:

No values found

In this example, an empty list is created and assigned to the variable empty_list. The max() function is then used to find the highest value in the list, but since the list is empty, the default value of “No values found” is returned instead. Finally, the default value is printed on the console.

Example 5: Using max() with mixed data types


 
mixed_list = ["a", 2, "c", 4.5, True]
max_value = max(mixed_list)
print(max_value)
Copy code

Output:

TypeError: ‘>’ not supported between instances of ‘int’ and ‘str’

In this example, a list containing values of different data types is created and assigned to the variable mixed_list. The max() function is then used to find the highest value in the list, but since the list contains values of different data types (int, str, float, bool), a TypeError is raised because comparison is not supported between these data types.

Endnotes

In conclusion, the max() function is often used in data analysis, mathematics, and programming to retrieve the highest value in a data set. This article helped you understand how and why the max() method is used in Python.

Check Our More Python Blogs

How to Check if a Python String is a Palindrome

How to Generate Random Numbers in Python?

For Loop in Python (Practice Problem) – Python Tutorial

Calculator Program in Python: A Step-By-Step Guide

Conditional Statements in Python – Python Tutorial

How to Find an Armstrong Number Using Python

Difference Between Module and Package in Python

Constructors in Python: Definition, Types, and Rules

Difference Between Methods and Functions in Python

Star Pattern in Python

Methods to Check for Prime Numbers in Python

Top 7 Online Python Compiler Picks for 2024

How to Compute Euclidean Distance in Python

Bubble Sort Algorithm in Python

How to Find the Factorial of a Number Using Python

Find the Second Occurrence of a Substring in Python String

Types of Functions in Python

Difference Between Mutable and Immutable in Python

ord() and chr() Function in Python

FAQs

What happens if multiple maximum values are in a list?

If there are multiple maximum values in a list, the max() function will return the first maximum value it encounters.

How does the max() function handle negative numbers?

The max() function handles negative numbers in the same way as positive numbers. It returns the largest value, regardless of whether it is positive or negative.

Can the max() function be used with non-numeric values?

Yes, the max() function can be used with non-numeric values, such as strings or tuples. When used with non-numeric values, the max() function returns the value that would last if the values were sorted alphabetically.

What happens if I use the max() function with an empty list?

If you use the max() function with an empty list and do not provide a default value, a ValueError will be raised.

Can I use the max() function with custom key functions?

Yes, the max() function can be used with custom key functions to define how the elements in the iterable are compared. The key function should take one argument and return a value that will be used to determine the order of the elements.

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio