Open In App

Python – max() function

Last Updated : 30 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Python max() function returns the largest item in an iterable or the largest of two or more arguments.

It has two forms.

  • max() function with objects
  • max() function with iterable

Python max() function With Objects

Unlike the max() function of C/C++, the max() function in Python can take any type of object and return the largest among them. In the case of strings, it returns the lexicographically largest value.

Syntax : max(arg1, arg2, *args[, key]) 

Parameters : 

  • arg1, arg2 : objects of the same datatype
  • *args : multiple objects
  • key : function where comparison of iterable is performed based on its return value

Returns : The maximum value 

Example of Python max() function

We can use max() function to locate the largest item in Python. Below are some examples:

Example 1: Finding the Maximum of 3 Integer Variables

The code initializes three variables with values (var1 = 4, var2 = 8, var3 = 2) and then finds the maximum value among them using the max() function. The result, that is 8, is printed to the screen.

Python3




var1 = 4
var2 = 8
var3 = 2
 
max_val = max(var1, var2, var3)
print(max_val)


Output

8



Example 2: Finding the Maximum of 3 String Variables

By default, it will return the string with the maximum lexicographic value. In this example, as max() is used to locate the largest item in Python, we are using max() to find maximum out of 3 string variable.

Python3




var1 = "geeks"
var2 = "for"
var3 = "geek"
 
max_val = max(var1, var2, var3)
print(max_val)


Output

geeks



Example 3: Finding the Maximum of 3 String Variables According to the Length

We will be passing a key function in the max() method. 

Python3




var1 = "geeks"
var2 = "for"
var3 = "geek"
 
max_val = max(var1, var2, var3,
            key=len)
print(max_val)


Output

geeks



Example 4: Python max() Exception

If we pass parameters of different datatypes, then an exception will be raised.

Python3




integer = 5
string = "geek"
 
max_val = max(integer, string)
print(max_val)


Output

TypeError: '>' not supported between instances of 'str' and 'int'

Example 5: Python max() Float

In this example, max() function is used to find and store the maximum value within this list, which is 1.3.

Python3




list = [1.2, 1.3, 0.1]
max_value = max(list)
print(max_value)


Output

1.3



Example 6: Python max() Index

In this example, we are using max() to finds and prints the position of the maximum value in a given list.

Python3




# function to find minimum and maximum position in list
def maximum(a, n):
 
    # inbuilt function to find the position of maximum
    maxpos = a.index(max(a))
 
    # printing the position
    print ("The maximum is at position", maxpos + 1)
 
# driver code
a = [3, 4, 1, 3, 4, 5]
maximum(a, len(a))


Output

The maximum is at position 6



max() Function With iterable In Python

When an iterable is passed to the max() function it returns the largest item of the iterable. 

Syntax : max(iterable, *iterables[, key, default]) 
Parameters : 

  • iterable : iterable object like list or string.
  • *iterables : multiple iterables
  • key : function where comparison of iterable is performed based on its return value
  • default : value if the iterable is empty

Returns : The maximum value. 

Example 1: Finding the Lexicographically Maximum Character in a String

This code defines a string “GeeksforGeeks” and then uses the max() function to find and print the character with the highest Unicode value within the string, which is ‘s’.

Python3




string = "GeeksforGeeks"
 
max_val = max(string)
print(max_val)


Output

s



Example 2: Finding the Lexicographically Maximum String in a String List

This code creates a list of strings, “string_list,” containing [“Geeks”, “for”, “Geeks”]. It then uses the max() function to find and print the maximum string based on lexicographic order

Python3




string_list = ["Geeks", "for", "Geeks"]
 
max_val = max(string_list)
print(max_val)


Output

for



Example 3: Finding the Longest String in a String List

In this code, there is a list of strings, “string_list,” containing [“Geeks”, “for”, “Geek”]. It utilizes the max() function with the key=len argument, which compares the strings based on their lengths.

Python3




string_list = ["Geeks", "for", "Geek"]
 
max_val = max(string_list, key=len)
print(max_val)


Output

Geeks



Example 4: If the Iterable is Empty, the Default Value will be Displayed

This code initializes an empty dictionary, “dictionary,” and then uses the max() function with the default argument set to a default value, which is the dictionary {1: "Geek"}.

Python3




dictionary = {}
 
max_val = max(dictionary,
            default={1: "Geek"})
print(max_val)


Output

{1: 'Geek'}





Previous Article
Next Article

Similar Reads

Numpy recarray.max() function | Python
In numpy, arrays may have a data-types containing fields, analogous to columns in a spreadsheet. An example is [(a, int), (b, float)], where each entry in the array is a pair of (int, float). Normally, these attributes are accessed using dictionary lookups such as arr['a'] and arr['b']. Record arrays allow the fields to be accessed as members of th
4 min read
Python String Methods | Set 3 (strip, lstrip, rstrip, min, max, maketrans, translate, replace & expandtabs())
Some of the string methods are covered in the below sets.String Methods Part- 1 String Methods Part- 2More methods are discussed in this article1. strip():- This method is used to delete all the leading and trailing characters mentioned in its argument.2. lstrip():- This method is used to delete all the leading characters mentioned in its argument.
4 min read
List Methods in Python | Set 1 (in, not in, len(), min(), max()...)
List methods are discussed in this article. 1. len() :- This function returns the length of list. List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1] print(len(List)) Output: 10 2. min() :- This function returns the minimum element of list. List = [2.3, 4.445, 3, 5.33, 1.054, 2.5] print(min(List)) Output: 1.054 3. max() :- This function returns the maximum eleme
2 min read
Python String | max()
max() is an inbuilt function in Python programming language that returns the highest alphabetical character in a string. Syntax: max(string) Parameter: max() method takes a string as a parameter Return value: Returns a character which is alphabetically the highest character in the string. Below is the Python implementation of the method max() Pytho
1 min read
Python | Find Min/Max in heterogeneous list
The lists in Python can handle different type of datatypes in it. The manipulation of such lists is complicated. Let's say we have a problem in which we need to find the min/max integer value in which the list can contain string as a data type i.e heterogeneous. Let's discuss certain ways in which this can be performed. Method #1 : Using list compr
7 min read
Python | Pandas Series.max()
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.max() function return the maximum of the underlying data in the given Series ob
3 min read
Python | Pandas dataframe.max()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.max() function returns the maximum of the values in the given object. If the input is a series, the method will return
2 min read
Python | Pandas Index.max()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Index.max() function returns the maximum value of the Index. The function works with both numerical as well as the string type ob
2 min read
Python | Pandas TimedeltaIndex.max
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas TimedeltaIndex.max() function return the maximum value of the TimedeltaIndex object or maximum along an axis. Syntax : TimedeltaI
2 min read
Use of min() and max() in Python
Prerequisite: min() max() in Python Let's see some interesting facts about min() and max() function. These functions are used to compute the maximum and minimum of the values as passed in its argument. or it gives the lexicographically largest value and lexicographically smallest value respectively, when we passed string or list of strings as argum
2 min read
Practice Tags :
three90RightbarBannerImg