Python min() function returns the smallest of the values or the smallest item in an iterable passed as its parameter.
Python min() Function Example
Python3
print ( min ([ 1 , 2 , 3 ])) |
Output:
1
There are two types of usages of the Python min() function:
- min() functions with objects
- min() functions with an iterable
Python min() Function Syntax
The min() function in Python can take any type of object of similar type and returns the smallest among them. In the case of strings, it returns lexicographically the smallest value.
Syntax: min(a, b, c, …, key=func)
- a, b, c, .. : similar type of data.
- key (optional): A function to customize the sort order
Return: Returns the smallest item.
Using Python min() function to find the minimum item among the similar types of objects.
Python3
# printing the minimum of # 4, 12, 43.3, 19, 100 print ( min ( 4 , 12 , 43.3 , 19 , 100 )) |
Output:
4
Python min() Function with an Iterable
The Python min() function can take any iterable and returns the smallest item in an iterable.
Syntax: min(iterable, key=func)
- iterable: Any Python iterable (ex.: list, tuple, set, dict, etc.)
- key (optional): function to customize the sorting of items in an iterable.
Return: Returns the smallest item in an iterable.
Using Python min() function to find the minimum element in an iterable.
Python3
# minimum item in list print ( min ([ 1 , 2 , 3 ])) # minimum item in dict print ( min ({ 'a' : 1 , 'b' : 2 , 'c' : 3 })) # minimum item in tuple print ( min (( 7 , 9 , 11 ))) |
Output:
1
a
7
Customizing the sort order
To customize the sort order, a key parameter is passed to the min() function. Using Python min() function to find the string with minimum length among multiple strings.
Python3
# find the string with minimum length s = min ( "GfG" , "Geeks" , "GeeksWorld" , key = len ) print (s) |
Output:
GfG
Exception Raised: Demonstrating TypeError when using min() function.
TypeError is raised when conflicting data types are compared.
Python3
# printing the minimum of 4, 12, 43.3, 19, # "Lazyroar" Throws Exception print ( min ( 4 , 12 , 43.3 , 19 , "Lazyroar" )) |
Output:
TypeError: '<' not supported between instances of 'str' and 'int'
Demonstrating ValueError when using min() function
ValueError is raised when an empty iterable is passed without the default argument.
Python3
L = [] # printing the minimum empty list print ( min (L)) |
Output:
ValueError: min() arg is an empty sequence