Python min() Function
Returns the smallest value in a list of parameters or in an iterable.
Syntax
Python
Copy Code
min(iterable1, iterable2, ..., key = None, default = None) min(item1, item2, ..., key = None)
Parameters
Parameter | Description |
---|---|
iterable1, iterable2, ... |
Required. A list of iterables containing the items to be compared. In this form at least one iterable must be passed to the function, and the smallest item from all items in all iterables will be returned. |
item1, item2, ... |
Required. A list of items to be compared. In this form at least 2 items must be passed to the function. |
key |
Optional. A function that returns, for each item, a representative value for that item for use in the comparison. |
default |
Optional. If the iterable is empty then this value is returned. |
Example
Python
Copy Code
print(min(1, 3, 2)) nums = [10, 40, 30, 20] print(min(nums))
Output
1 10
Notes
If the iterable is empty, min()
will throw a ValueError
exception unless a
default value is provided:
Python
Copy Code
try: min([]) except ValueError: print('An empty collection has no min value.') print(min([], default = 0))Output:
An empty collection has no min value. 0
If the key parameter is used to provide a function that returns a number used to determine the
maximum value in the collection. In the following example, the len()
function is used
to determine which string is the longest.
Example
Python
Copy Code
myList = ['small', 'bigger', 'very big'] print(min(myList, key = len))Output:
small