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)
val1,val2,val3…RequiredValues that need to be compared
keyOptionalA 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)
iterableRequiredAn iterable with one or multiple items
keyOptionalA function specifying custom comparison criteria to find the minimum value.
The default value is None.
defaultOptionalA 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)
>>> min('a', 'b', 'c', 'd')

Passing an iterable (for example an list) as an argument to the min() function.

>>> l= ['a', 'b', 'c', 'd']
>>> min(l)
>>> l= [12, 10, 56, 32]
>>> min(l)

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)

Using len as key parameter to get the shortest string.

>>> l= ['pencil', 'programmer']
>>> min(l, key=len)

We can also use the user-defined lambda function as the key to get desired value as the min result.

>>> brands = [('samsung', 4),
              ('Nokia', 5)]
>>> print(min(brands, key=lambda x: x[1]))
('Mi', 3) 

Leave a Reply