The min() function returns:
- the smallest of two or more vales (such as numbers, strings, etc.)
- the smallest item in an iterable (such as list, tuple etc.)
Syntax for two or more values
min(val1, val2, val... ,key)max() Parameters
Python min() function parameters:
| Parameter | Condition | Description |
|---|---|---|
val1,val2,val3... |
Required | Two or more values to compare |
key |
Optional | A function to specify the comparison criteria. Default value is None. |
min() Return Value
Python min() function returns the smallest element.
Syntax for iterables
min(iterable, key, default)min() Parameters
Python min() function parameters:
| Parameter | Condition | Description |
|---|---|---|
iterable |
Required | Any iterable, with one or more items to compare |
key |
Optional | A function to specify the comparison criteria. Default value is None. |
default |
Optional | A value to return if the iterable is empty. Default value is False. |
min() Return Value
Python min() function returns the smallest item in the iterable.
Examples
Example 1: Get the smallest String with min() function
The min() function compares the strings lexicographically (i.e., it compares the strings character by character from left to right, alphabetically). The first string where a character is lexicographically smaller than the corresponding character in the other string is returned as the minimum.
str1 = "Tutorial"
str2 = "Reference"
str3 = "for"
str4 = "you!"
min_val = min(str1, str2, str3, str4)
print(min_val) # Output: 'you!'output
you!Notice that the example returns you! because it is the string that comes first in lexicographical order among the provided strings
Another example:
str1 = "aaa"
str2 = "aaaa"
str3 = "AAA"
str4 = "AAAA"
min_val = min(str1, str2, str3, str4)
print(min_val) # Output: 'aaaa'output
aaaaExample 2: Get the smallest string with min() function and key parameter
You can specify the comparison criteria by using the key parameter of the min() function.
For example, we can get the shortest string by specifying the function len for the key parameter:
str1 = "Tutorial"
str2 = "Reference"
str3 = "for"
str4 = "you!"
min_val = min(str1, str2, str3, str4, key=len)
print(min_val) # Output: 'for'output
forExample 3: Get the minimum number of two or more values
If you specify two or more values, the smallest value is returned.
x = min(10, 20, 30)
print(x) # Output: 10output
10Example 4: Get the minimum item in a List
For example, get the minimum number from a list of numbers:
number = [3, 2, 8, 5, 10, 6]
smallest_number = min(number)
print(smallest_number) # Output: 2output
2For example, get the smallest string (ordered alphabetically) from a list of strings:
languages = ["Python", "Java", "JavaScript", "Rust"]
smallest_string = min(languages)
print(smallest_string) # Output: Javaoutput
JavaExample 5: use min() function with dictionary
In the case of dictionaries, min() returns the smallest key.
Let's use the key parameter in the min() function to find the dictionary key that is associated with the highest value.
square = {2: 4, -3: 9, -1: 1, -2: 4}
key1 = min(square)
print("The smallest key:", key1) # Output: -3
key2 = min(square, key = lambda k: square[k])
print("The key with the smallest value:", key2) # Output: -1
print("The smallest value:", square[key2]) # Output: 1output
The smallest key: -3
The key with the smallest value: -1
The smallest value: 1Observe that:
- The second
min()function use the lambda function passed to thekeyparameter.
Example 6: empty iterable and min() function
If the iterable is empty, a ValueError is raised.
my_list = []
x = min(my_list) # Triggers ValueError: min() arg is an empty sequence
print(x) output
Traceback (most recent call last):
File "main.py", line 2, in <module>
x = min(my_list) # Triggers ValueError: min() arg is an empty sequence
ValueError: min() arg is an empty sequenceTo avoid such exception, add default parameter. The default parameter specifies a value to return if the provided iterable is empty.
If the iterable is empty, a ValueError is raised.
my_list = []
x = max(my_list, default='0')
print(x) output
0Example 7: Find Minimum with Custom Function
You give a user-defined function as key parameter of min() function for making comparisons:
For example, find out who is the youngest student in the given list of students:
def myFunc(elem):
return elem[1] # return age
students = [('Ryan', 35), ('Tom', 25), ('Charlie', 30)]
youngest_one = min(students, key=myFunc)
print(youngest_one) # Output: ('Tom', 25)output
('Tom', 25)Example 8: Find Minimum with lambda
A key function may also be created with the lambda expression. It allows us to in-line function definition.
As in the example7, find out who is the youngest student in the given list of students:
def myFunc(elem):
return elem[1] # return age
students = [('Ryan', 35), ('Tom', 25), ('Charlie', 30)]
youngest_one = min(students, key=lambda student: student[1])
print(youngest_one) # Output: ('Tom', 25)output
('Tom', 25)Example 9: Find Minimum of Custom Objects
Now, let's create a list of students (as a custom object) and find out who is the youngest student.
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return repr((self.name, self.age))
students = [Student('Ryan', 35), Student('Tom', 25), Student('Charlie', 30)]
youngest_one = min(students, key=lambda student: student.age)
print(youngest_one) # Output: ('Tom', 25)output
('Tom', 25)