python min and max

Python min() and max() Functions

Python min() and max() are built-in functions in python which returns the smallest number and the largest number of the list respectively, as the output. Python min() can also be used to find the smaller one in the comparison of two variables or lists. However, Python max() on the other hand is used to find the bigger one in the comparison of two variables or lists.

The syntax for python min() function is:

min(iterable[, default= object, key=func]) : value

The syntax for python max() function is:

max(iterable[, default= object, key=func]) : value

The iterable parameter can be an object like string, list, tuple or a map etc. The default parameter consists of a default value which is returned when the iterable parameter is null, otherwise an exception ValueError is thrown in the other case. The key is referred to as the parameter which checks for the order of sorting. Min() calculates the minimum number as an output and max() computes the maximum number out of all in the list.

Python program to understand the use of min() Function

a = min(5, 67, 23, 10, 9, 2)
print(a)

The output of the above python program will be:

2

Python program to understand the use of max() Function

a = max(5, 67, 23, 10, 9, 2)
print(a)

The output of the above python program will be:

67

Python min() and max() works well for data types such as string well too. Let us see a program below to understand the use of the min() function with strings:

Program Example 1:

a = min("abc", "abcd", "abcde")
print(a)

The output of the above python program will be:

abc

Program Example 2:

a = max("abc", "abcd", "abcde")
print(a)

The output of the above python program will be:

abcde

Some Exceptions while using min() and max() built-in functions

TypeError Exception: This exception occurs while the user tries to compare the two data types. For example min((“abc”, “abcd”, 23, 12). In this case, the user will get run time exception as an error as it is impossible to find the smallest between two different data types. Hence, it is always advisable to avoid such errors and use proper data types while making comparisons or wanting an output.

Example to use the min() and max() functions in python

x= ["abc", "abcd", "abcde", "b"]
y="abc"
print(max(x)) 
print(min(x)) 
print(max(y)) 
print(min(y))

The output of the above python program will be:

b
abc
c
a

Leave a comment

Your email address will not be published.