Max() Function In Python

Function Name:


Function Overview:

  • The python built-in function max() returns the maximum value of a given sequence or the maximum value among a given set of numbers.


  • An iterable or one or more objects – if an iterable is sent as the parameter, maximum value of the iterable will be returned. Else the maximum value among the objects will be returned.
  • key – a function defining the semantics of key extraction which takes one parameter and returns a value.
  • default – an object that is to be returned if the iterable is empty. If the default value is not provided and an empty iterator is passed, Python will raise a ValueError.

Return value:

  • Returns the maximum value from a set of objects or from a Python iterable.


  • Will raise a ValueError if the iterable passed is empty.

Example – Find the maximum value amongst the numbers passed as parameters to the max() function:

# Example Python Program to find the maximum

# of 'n' numbers using the built-in Python function max()


# A set of numbers

n1 = 2;

n2 = 40;

n3 = 6;

n4 = -6;

n5 = 0;


# Maximum value found

maximum         = max(n1, n2, n3, n4, n5);

print("Maximum value amongst the given numbers:");




Maximum value amongst the given numbers:



Example – Find the maximum value of numbers from a Python sequence

# Example Python Program to find the maximum

# of 'n' numbers from a sequence

# using the built-in Python function max()

listOfNumbers   = [-5, -9, 1, -12, 9, 18, 12];

maximum         = max(listOfNumbers);

print("Maximum value of the given number sequence:");




Maximum value of the given number sequence:


Example-To find the object with a maximum key value:

The example below uses a lambda function as the value for the key parameter. The function does key extraction for the Student object. Though in this example the maximum value is determined in lexicographical order, by changing the key to scores(by making the key function return id or scores) it is possible to find the student who has scored the maximum.

class Student:

    # init function

    def __init__(self, name, id):   = name;     = id;


    # Print student details

    def printDetails(self):




    # String representation of the object

    def __str__(self):



# Create student instances

student1 = Student("Mike, Francis", 112);

student2 = Student("Andrew, Joseph", 113);

student3 = Student("Jennifer, May", 114);


# Select a student object that ranks high lexicographically

highest = max(student1, student2, student3, key=lambda;




Mike, Francis


Copyright 2022 ©