Methods and Functions

Python max()

Python max() built-in function is used to return the largest item from the passed iterable objects. Python max function takes an input and returns the item with the highest value in that iterable.

The main reason Python is regarded as one of the most user-friendly and easy-to-learn programming languages is that it includes a variety of built-in functions that are really useful. Python max() is one such built-in Python function that can be beneficial for analyzing data. It operates in the reverse logic of Python’s min() function. Instead of looking for the smallest object, it looks for the largest item in the iterable.

max in python, python max

Python max

This function computes the maximum of the values passed as arguments. If the argument passed is a string, then alphabetically the largest value is been displayed. It can also be used to determine the largest object with respect to two or more parameters. When multiple iterables are provided as parameters, the greatest value of the list among the other list items is returned.

Let us look at a simple example to understand the exact functioning of Python max().

Example of max in python

                    

# Python program to illustrate max()
num = [2, 6, 9, 1, 0, 4]
print('Largest value is:', max(num))

letters = ['a', 'f', 'r', 'j', 'l']
print('Highest letter in alphabetic order is:', max(letters))

txt = 'Python'
print('Largest letter:', max(txt))

Output

                    

Largest value is: 9
Highest letter in alphabetic order is: r
Largest letter: y

Just like the Python min() function, Python max() also has 2 forms of syntax:

                    

# Find the largest item in an iterable
max(iterable, *iterables, key, default)


# Find the largest item between 2 or more objects
max(args1, args2, *args, key)

1. Python max with iterable arguments

  • Syntax

The syntax for the Python max() function is as follows:

                    

max(iterable, *iterables, key, default)

When max() is called with an iterable, it returns the object with the largest item. If the iterable is empty, the default value (if specified) is returned; otherwise, a ValueError exception is triggered.

When called with many input iterables, Python max() returns the largest value.

  • max() Parameters

iterable = a type of object such as a list, tuple, set, dictionary, etc.

*iterables (optional) = any number of iterables; more than one iterables

key (optional) = key function in which iterables are supplied and a comparison is made based on their return value

default (optional) = The value that will be used if the specified iterable is empty.

Return value of max in python

The max() function returns the largest element/item/value from an iterable

Example 1

                    

# largest item in a list
num = [23, 4, 67, 43, 60]
a = max(num)   # this is interpreted as -> a = max(list_iterable)
print("The largest number is:", a)

# largest string in a list
cars = ['Audi', 'Ferrari', 'BMW', 'Jaguar']
print("The largest string is:", max(cars))

Output

                    

The largest number is: 67
The largest string is: Jaguar

Example 2

                    

# largest item based on the key specified
city = ['Mumbai', 'New Delhi', 'New York', 'Paris', 'Chennai']
maximum = max(city, key = len)
print('Highest string based on length is:', maximum)

Output

                    

Highest string based on length is: New Delhi

Example 3

                    

# specifying default value
my_list = []
z = max(my_list, default = 'No elements')
print('Maximum value:', z)

Output

                    

Maximum value: No elements

Example 4

                    

# max() in dictionaries
cubes = {1: 1, 2: 8, 3: 27, -1: -1, -2: -8, -3: -27}

# largest key in dict
print('Largest key is:', max(cubes))

# key whose value is largest
a = max(cubes, key = lambda k: cubes[k])
print('The key with the largest value:', a)

# largest value
print('Largest value:', cubes[a])

Output

                    

Largest key is: 3
The key with the largest value: 3
Largest value: 27

2. Python max without iterable arguments

  • Syntax

                    

max(args1, args2, *args, key)

The first two parameters are essential in this case: if the objects you’re passing aren’t iterable, then you must at least specify two of them for max() to have something to compare.

The Python max() function frequently employs element-wise comparison to order results when many arguments are passed. This means that it will compare the first element of each object; if one is larger than the other, max() will return the object with the largest first element. However, if the two components are the same, max() will move on to the second element in each object and compare those.

  • max() Parameters

args1 = an object; can be an integer, a string, or anything else.

args2 = an object; can be integers, strings, etc.

*args (optional) = Any extra items to compare.

key (optional) = key function in which each argument is passed and a comparison is made based on its return value.

  • Return value from max()

Python max() returns the smallest argument from a set of many arguments passed to it.

Example

                    

result = max(4, -2, 8, 13, 0, -9)
print('Maximum number is:', result)

Output

                    

Maximum number is: 13

Exceptions while using max()

  1. ValueError Exception

If you pass max() an empty iterable as an argument, it will throw a ValueError. The arguments to max() cannot be null.

Example

                    

cars = []
print('Largest string is:', max(cars))

Output

                    

Traceback (most recent call last):
File "", line 2, in 
ValueError: max() arg is an empty sequence

To avoid this error, Python max() accepts the default parameter. Even if the list is empty, max() returns the default value.

  1. TypeError Exception

When we do not pass anything to the max() function, which requires at least one argument, we get a TypeError. OR when two different types of data are compared.

Example 1

                    

a = max()
print('Highest value:', a)

Output

                    

Traceback (most recent call last):
File "", line 1, in 
TypeError: max expected 1 argument, got 0

Example 2

                    

a = max(20, 43, 5, 'Hello', 'John', 'Jack')
print("Maximum value is : ", a)

Output

                    

Traceback (most recent call last):
File "", line 1, in 
TypeError: '<' not supported between instances of 'str' and 'int'

  1. NameError Exception

The NameError exception occurs if the iterable or the argument passed to the max() function is not been defined before.

Example

                    

a = max(num, default = 'No elements')
print('Highest value:', a)

Output

                    

Traceback (most recent call last):
File "", line 1, in 
NameError: name 'num' is not defined

FAQs on Python max function

Q1. What is max() in Python?

Python max() built-in function is used to return the largest item from the passed iterable objects. This function computes the maximum of the values passed as arguments. If the argument passed is a string, then alphabetically the largest value is been displayed.

Q2. How do you find the max of a list in Python?

To find the maximum element in a list, we pass the entire list to the Python max() function. Let us consider an example to understand this concept.

                    

marks = [78, 87, 83, 94, 96, 88, 79, 92]
print('Highest marks:', max(marks))

char = ['A', 'G', 'R', 'D', 'K']
print('Highest alphabet in seq:', max(char))

Output

                    

Highest marks: 96
Highest alphabet in seq: R

Q3. How do you find out the max value of an object in Python?

To find out the max value of an object we have to provide the key argument to the Python max() function.

Example

                    

class Data:
    id = 0
    def __init__(self, i):
        self.id = i

    def __str__(self):
        return 'Data[%s]' % self.id

def get_data_id(data):
    return data.id

# max() with objects and key argument
list_objects = [Data(5), Data(10), Data(-5), Data(-10)]
print(max(list_objects, key=get_data_id))

Output

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

Your email address will not be published. Required fields are marked *

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.