The min()
function is used to retrieve the smallest item in an iterable object such as a list, tuple,dictionary, etc.
print(min(10, 2, 0, 4, 8, 6))
It is also used to check the smallest of two or more arguments.
print(min(1, 2))
print(min(7, 3, 1, 7))
min(iterable, *args, key = None, default=None)
iterable | The iterable object from which the smallest item is to be retrieved . |
args | Arbitrary two or more objects to be compared . |
key | A function to be used as the comparison criteria. |
default | The default value to be returned in case the iterable is empty. It is only relevant if the arguments are in an iterable. |
Note: the iterable
argument and the args
arguments are exclusive. If one is specified the other one is ommited.
The function returns the smallest value in the iterable or the smallest of the given positional argument.
Examples:
min(1, 2, 3, 0)
//0
min([6, 9, 5, 3])
//3
min(1.0, -5.2, -3.6, 3.4)
//-5.2
min(['a', 'b', 'c', 'd', 'f'])
//'a'
min(0, 1.6, 5, -3.5, -2, -3)
//-3.5
The default argument is used to specify a default value that will be returned if the iterable is empty. If no default
argument is provided and the iterable is empty, a ValueError
will be raised. Example:
min([])
//ValueError: min() arg is an empty sequence
min([], default = "empty")
//Empty
The key argument is optional and specifies the criteria to be used for comparison. If it is not given then the elements will be compared using their default comparison operation. For example numerical values will be compared based on their mathematical values, strings will be compared alphabetically while sequence and collections such as lists and sets will be compared based on each of their element's values.
All the items in the iterable needs to be comparable for the min()
function to work, otherwise a TypeError
will be raised. For example , while we can compare an integer to a float, it would be impossible to compare an integer to a string. Example:
min([1, 2,'3'])
//TypeError: '<' not supported between instances of 'int' and 'str'
The key argument can be used to overwrite the default comparison criteria. It is normally a function which gets called with all the elements in the iterable and the returned values are used in comparison instead of the elements themselves. For example we can check the smallest list by length in a two dimensional list by specifying the builtin len
function as the key .
Examples:
min([[1, 2], [5, 6, 7], [10], [15, 20, 30]], key = len)
//[10]
min(["Python", "Javascript", "Kotlin", "Ruby"], key = len)
//'Ruby'
min([1, -4, 1, 6, -9, 7], key = abs)
//1
The lambda functions are commonly used to create keys on the fly for this type of functions. For example, the example below will return the smallest object in the list based on the objects' second value.:
min(('Java', 4), ('Python', 1), ('C++', 7), ('Ruby', 3), ('Kotlin', 2), key = lambda x: x[1])
//('Python', 1)
You can check on min's counterpart, the max function.