Python min() – Examples

Python min()

Python min() function is used to find the minimum of a given iterable, or two or more arguments.

We can provide either an iterable; or two or more items as arguments to min() function, but not mix iterable and the other items.

Optionally, we can also give a named key function, based on whose return value the items in the iterable or the arguments are compared and the minimum is found.

Syntax – min()

The syntax of min() function is

min(iterable, *[, key, default])
# or
min(arg1, arg2, *args[, key])

We can also provide a default value, which will be returned if there are no items in the iterable.

Example 1: Find Minimum of Iterable

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}.')
Run

Output

Smallest number in the list is : 18.

Example 2: Find Minimum of Two or More Items

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}.')
Run

Output

Smallest number in the list is : 18.

Example 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}.')
Run

Output

Number that leaves smallest reminder is : 41.

Example 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}.')
Run

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.