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
Find the Second Occurrence of a Substring in Python String
During Python programming, you will come across instances where you would need to find the second occurrence of a substring in Python a given string. For example, finding the second...read more
How to use pass statement in Python
How to use pass statement in Python
A pass statement in Python is a null statement that act as a placeholder for future code. In this article, we will briefly discuss how to use pass statement with...read more
Introduction to Recursion Functions in Python
Introduction to Recursion Functions in Python
When programming, in many places you would have implemented a function that invokes or calls another function. However, when a function calls itself we call that recursion.
Recommended online courses

Best-suited Python courses for you

Learn Python with these high-rated online courses

Free
6 weeks
– / –
2 weeks
– / –
16 weeks
1.7 K
3 months
– / –
– / –
4.24 K
2 weeks
3 K
3 weeks
– / –
4 months

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 Check if a Python String is a Palindrome
A palindrome is a sequence of the word, phrases, or numbers that read the same backward as forward. In this article, we will discuss different methods how to check if...read more

How to Generate Random Numbers in Python?
How to Generate Random Numbers in Python?
In Data Science or Statistics, there are various instances where a programmer might need to work with random inputs. Python offers many predefined functions to generate and use random data....read more

For Loop in Python (Practice Problem) – Python Tutorial
For Loop in Python (Practice Problem) – Python Tutorial
For loops in Python are designed to repeatedly execute the code block while iterating over a sequence or an iterable object such as a list, tuple, dictionary, or set. This...read more

Calculator Program in Python: A Step-By-Step Guide
Calculator Program in Python: A Step-By-Step Guide
Looking for a powerful and user-friendly calculator program in Python? In this blog, we will discuss three different methods for calculator programs in Python. A calculator performs arithmetic operations along...read more

Conditional Statements in Python – Python Tutorial
Conditional Statements in Python – Python Tutorial
A conditional statement as the name suggests itself, is used to handle conditions in your program. These statements guide the program while making decisions based on the conditions encountered by...read more

How to Find an Armstrong Number Using Python
How to Find an Armstrong Number Using Python
Learn how to find Armstrong numbers using Python with our step-by-step guide. Discover the algorithm to identify these special numbers, which are equal to the sum of their own digits...read more

Difference Between Module and Package in Python
Difference Between Module and Package in Python
Confused with modules and packages in python, then this article is for you. This article briefly discusses the Difference Between Module and Package in Python. If you have a basic...read more

Constructors in Python: Definition, Types, and Rules
Constructors in Python: Definition, Types, and Rules
Constructor in python is a special method that is called when an object is created. The purpose of a python constructor is to assign values to the data members within...read more

Difference Between Methods and Functions in Python
Difference Between Methods and Functions in Python
In Python, methods and functions have similar purposes but differ in important ways. Functions are independent blocks of code that can be called from anywhere, while methods are tied to...read more

Star Pattern in Python
Star Pattern in Python
Pattern programs in Python are a type of problem that uses nested loops to produce different patterns of numbers, stars (*), or other characters. In this blog, we will dive...read more

Methods to Check for Prime Numbers in Python
Methods to Check for Prime Numbers in Python
Prime numbers are the building blocks of mathematics, and they have fascinated mathematicians for centuries. Regarding Python programming, there are different methods to check whether the given number is a...read more

Top 7 Online Python Compiler Picks for 2024
Top 7 Online Python Compiler Picks for 2024
Are you tired of installing Python on your computer? Don’t worry; we’ve got you covered with the top 7 online Python compilers for 2024! These compilers are like having a...read more

How to Compute Euclidean Distance in Python
How to Compute Euclidean Distance in Python
Euclidean Distance is one of the most used distance metrics in Machine Learning. In this article, we will discuss Euclidean Distance, how to derive formula, implementation in python and finally...read more

Bubble Sort Algorithm in Python
Bubble Sort Algorithm in Python
The Bubble Sort algorithm is a simple sorting method that iterates through a given list, compares every pair of neighboring items, and exchanges them if they are out of order....read more

How to Find the Factorial of a Number Using Python
How to Find the Factorial of a Number Using Python
In this article, we will discuss different methods to find the factorial of a number in python using for, while, ternary operator and math module. While practicing Python programming as...read more

Find the Second Occurrence of a Substring in Python String
Find the Second Occurrence of a Substring in Python String
During Python programming, you will come across instances where you would need to find the second occurrence of a substring in Python a given string. For example, finding the second...read more

Types of Functions in Python
Types of Functions in Python
A function is a block of code in Python that performs a particular task. It may take zero or more inputs and may or may not return one or more...read more

Difference Between Mutable and Immutable in Python
Difference Between Mutable and Immutable in Python
Data types in Python are categorized into mutable and immutable data types. Mutable data type is those whose values can be changed, whereas immutable data type is one in which...read more

ord() and chr() Function in Python
ord() and chr() Function in Python
ord () and chr() functions of Python are built-in functions that are used to convert a character to an integer and vice-versa. In this article, we will learn how to...read more

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