The Python min()
function is a built-in function that returns the smallest item in an iterable or the smallest of two or more arguments. The iterable can be a list, tuple, set, or any other collection that can be iterated upon. If two or more arguments are provided, it returns the smallest of the arguments.
Syntax
min(iterable, *[, key, default]) min(arg1, arg2, *args[, key])
Parameters
iterable
– The iterable to find the minimum item in.arg1, arg2, *args
– The arguments to find the minimum of.key
– (Optional) A function that returns a value used to compare elements in the iterable or the arguments.default
– (Optional) The value to return if the iterable is empty.
Return Value
The min()
function returns the smallest item in the iterable or the smallest of the arguments.
Examples
Example 1: Finding the minimum item in a list
lst = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] print(min(lst))
Output:
1
In this example, we have defined a list lst
of numbers. Then we have used the min()
function to find the minimum item in the list and print it. The output is 1, which is the smallest number in the list.
Example 2: Finding the minimum of two or more arguments
print(min(1, 2, 3, 4, 5)) print(min(5, 4, 3, 2, 1))
Output:
1 1
In this example, we have used the min()
function to find the minimum of two or more arguments. In the first call, we have provided five numbers as arguments, and in the second call, we have provided the same five numbers in reverse order. The output of both calls is 1, which is the smallest of the arguments.
Example 3: Using the key parameter
lst = ['apple', 'banana', 'cherry', 'date'] print(min(lst, key=len))
Output:
date
In this example, we have defined a list lst
of strings. Then we have used the min()
function with the key
parameter to find the minimum item based on the length of the strings. The output is “date”, which has the shortest length of all the strings in the list.
Use Cases
The min()
function can be used in various scenarios, such as:
- Finding the minimum value in a list, tuple, set, or any other iterable
- Finding the minimum of two or more arguments
- Finding the item in an iterable with the minimum value based on a key function
- Setting a default value to return if the iterable is empty
In conclusion, the min()
function is a simple yet powerful function that can be used in a wide range of applications to find the smallest item in an iterable or the smallest of two or more arguments. It is an essential tool for every Python programmer.