Use of min() and max() in Python


In this article, we will be learning about min and max functions included in the Python Standard Library. It accepts infinite no of parameters according to the usage

Syntax

max( arg1,arg2,arg3,...........)

Return Value − Maximum of all the arguments

Errors & Exceptions: Here error is raised only in the scenario where the arguments are not of the same type. Error is encountered while comparing them.

Let’s see what all ways we can implement the max() function first.

Example

 Live Demo

# Getting maximum element from a set of arguments passed
print("Maximum value among the arguments passed is:"+str(max(2,3,4,5,7,2,1,6)))
# the above statement also executes for characters as arguments
print("Maximum value among the arguments passed is:"+str(max('m','z','a','b','e')))
# it can also a accept arguments mapped in the form of a list
l=[22,45,1,7,3,2,9]
print("Maximum element of the list is:"+str(max(l)))
# it can also a accept arguments mapped in the form of a tuple
l=(22,45,1,7,71,91,3,2,9)
print("Maximum element of the tuple is:"+str(max(l)))

Output

Maximum value among the arguments passed is:7
Maximum value among the arguments passed is:z
Maximum element of the list is:45
Maximum element of the tuple is:91

Here it is clearly observed that by the use of max function we can directly get the maximum values among the arguments without any comparison operations.

Similarly, we can implement the min() function here

Example

 Live Demo

# Getting maximum element from a set of arguments passed
print("Minimum value among the arguments passed is:"+str(min(2,3,4,5,7,2,1,6)))
# the above statement also executes for characters as arguments
print("Minimum value among the arguments passed is:"+str(min('m','z','a','b','e')))
# it can also a accept arguments mapped in the form of a list
l=[22,45,1,7,3,2,9]
print("Minimum element of the list is:"+str(min(l)))
# it can also a accept arguments mapped in the form of a tuple
l=(22,45,1,7,71,91,3,2,9)
print("Minimum element of the tuple is:"+str(min(l)))

Output

Minimum value among the arguments passed is:1
Minimum value among the arguments passed is:a
Minimum element of the list is:1
Minimum element of the tuple is:1

By using built-in functions like max() & min() we can directly obtain the corresponding maximum and minimum values without the actual implementation of the logic to make the comparison happen

Conclusion

In this article, we learnt the implementation of max and min function included in the Standard Python Library.

Updated on: 29-Aug-2019

285 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements