The built-in min() function in Python returns the item that has the lowest value.
- It returns the smallest value of two or more numbers passed as arguments.
- It returns the lexicographically smallest value if strings are passed as arguments.
- It returns the smallest item of an iterable such as list, set, etc.
min() Syntax and Parameters
The min()
function, in general, has two types of syntaxes. We can either pass multiple values separated by comma as separate arguments or all combined as an iterable.
For multiple individual values, the one which has smallest value will be returned.
min(val1,val2,val3… ,key)
Parameter | Condition | Description |
---|---|---|
val1,val2,val3… | Required | Values that need to be compared |
key | Optional | A function specifying custom comparison criteria to find minimum value. Default value is None . |
For an iterable, the item with the smallest value is returned.
min(val1,val2,val3… ,key)
Parameter | Condition | Description |
---|---|---|
iterable | Required | An iterable with one or multiple items |
key | Optional | A function specifying custom comparison criteria to find the minimum value. The default value is None . |
default | Optional | A value to return if the iterable is empty. The default value is False . |
Examples using min()
Passing multiple values separately to the min()
function.
>>> min(5, 7, 1, 2)
1
>>> min('a', 'b', 'c', 'd')
a
Passing an iterable (for example an list) as an argument to the min()
function.
>>> l= ['a', 'b', 'c', 'd']
>>> min(l)
a
>>> l= [12, 10, 56, 32]
>>> min(l)
10
Note: If you pass an empty iterable then the ValueError
exception is raised.
>>> l= []
>>> min(l)
ValueError: min() arg is an empty sequence
To solve this, we should specify a default value.
In that case, the interpreter instead of raising error will return the default value.
>>> l= []
>>> min(l, default=-1)
-1
Using len
as key
parameter to get the shortest string.
>>> l= ['pencil', 'programmer']
>>> min(l, key=len)
pencil
We can also use the user-defined lambda function as the key to get desired value as the min result.
>>> brands = [('samsung', 4),
('Mi',3),
('Nokia', 5)]
>>> print(min(brands, key=lambda x: x[1]))
('Mi', 3)