min() Built-in Function
Python min()
Python min() function is used to find the minimum of a given iterable, or two or more arguments.
In this tutorial, you will learn the syntax of min() function, and then its usage with the help of example programs.
Syntax of min()
The syntax of min() function is
min(iterable, *[, key, default])
# or
min(arg1, arg2, *args[, key])
where
Parameter | Description |
---|---|
iterable | An iterable like list, tuple, etc. |
arg1 , arg2 , ... | Values in which we have to find the maximum. |
default | A default value, which will be returned if there are no items in the iterable. |
key | [Optional] A key function based on whose return value the items in the iterable or the arguments are compared and the maximum is found. |
Examples
1: Find minimum of items in an list
In this example, we will take a list of numbers and find the smallest number in the list using min() function.
Python Program
a = [18, 52, 23, 41, 32]
smallest = min(a)
print(f'Smallest number in the list is : {smallest}.')
Output
Smallest number in the list is : 18.
2. Find minimum of two or more integers
In this example, we will take five numbers and find the smallest number of these using min() function.
Python Program
smallest = min(18, 52, 23, 41, 32)
print(f'Smallest number in the list is : {smallest}.')
Output
Smallest number in the list is : 18.
3. min() with key function
In this example, we will take a list of numbers and find the number which leaves smallest reminder when divided with 10, using min() function.
We will define a lambda function for key parameter that returns the reminder of the element in the list for comparison.
Python Program
a = [18, 52, 23, 41, 32]
keyfunc = lambda x: x % 10
smallest = min(a, key=keyfunc)
print(f'Number that leaves smallest reminder is : {smallest}.')
Output
Number that leaves smallest reminder is : 41.
4. min() with default value
In this example, we will take an empty list and find the smallest number of the list using min() function. Since the list is empty, if we set default parameter for the min() function, the default value is returned.
Python Program
a = []
smallest = min(a, default=0)
print(f'Smallest number in the list is : {smallest}.')
Output
Smallest number in the list is : 0.
Summary
In this tutorial of Python Examples, we learned the syntax of min() builtin function and how to use it, with the help of examples.