BlogsDope image BlogsDope

Python max() function

March 16, 2021 PYTHON FUNCTION 1021

There are many useful built-in functions provided by the Python library and one of these is the max() function. The max() function returns the largest item present in the passed iterable or object.

Python max() Syntax

The max() method can be used with any one of the following two syntaxes:

max(iterable, *iterables, key, default)

or

​max(arg1, arg2, *args, key)

Python max() Parameters

The first syntax is used to find the largest value in an iterable, and the parameters are as follows:

  • iterable - This parameter refers to a Python iterable such as list, tuple, set, dictionary, etc.
  • *iterables (optional) - This parameter is used to refer more than one iterables.
  • key (optional) - This parameter refers to the key function where the iterables are passed and comparison is performed based on its return value.
  • default (optional) - This parameter refers to the default value if the passed iterable is empty.

The second syntax is used to find the largest value among two or more arguments and has the following parameters:

  • arg1, arg2 - These parameters can be an object, numbers, strings, etc. 
  • *args (optional) - This refers to multiple objects to be compared.
  • key (optional) - This parameter refers to the key function where each argument is passed, and comparison is performed based on its return value.

Python max() Return Value

Based on the type of input values, the max() method can have following return values:

Input 
Return Value
Iterables
It returns the largest value in the iterable. If the iterable is empty then the default value is returned, otherwise, a ValueError exception is raised.
Other Arguments
It returns the largest among the passed arguments.

Python max() Examples

1. max() with iterables

# with string
#prints the lexographically maximum character in a string
st = "CodesDope"
print(max(st))

# with list
ls1 = [ 22, 45, 100, 14 ]
print(max(ls1))
ls2 = [ "a", "ab", "abc" ]
print(max(ls2, key = len))


# with tuple
tup = ( 5, 6, 9, 2 )
print(max(tup))

# with dictionary
d1 = {1: "one", 2: "two", 3: "three"}
print(max(d1))
d2 = {}
print(max(d2, default = {1 : "one"}) )

# Error for empty iterable
l = []
print(max(l))

Output:

s
100
abc
9
3
{1: 'one'}
ValueError: max() arg is an empty sequence

2. max() with other arguments

# with integers
print(max(50,60,70,80))

# with characters
# character with maximum ASCII value is returned
print(max("a", "b", "s", "P", "R"))

# with floating point value
print(max(3.14, 9.8, 6.63))

# type mismatch error
print(max(5, "a", 3.11))

Output:

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

In this way we have seen the working of the Python max() function and how it can be used to find the maximum value out of various Python objects.

Liked the post?
Zealous Learner.
Editor's Picks
0 COMMENT

Please login to view or add comment(s).