Skip to main content

Python min() Function

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.)
note

With optional key parameter, you can specify custom comparison criteria to find minimum value.

Syntax for two or more values

min(val1, val2, val... ,key)

max() Parameters

Python min() function parameters:

ParameterConditionDescription
val1,val2,val3...RequiredTwo or more values to compare
keyOptionalA function to specify the comparison criteria. Default value is None.

min() Return Value

Python min() function returns the smallest element.

danger

You have to specify minimum two values to compare. Otherwise, TypeError exception is raised.

Syntax for iterables

min(iterable, key, default)

min() Parameters

Python min() function parameters:

ParameterConditionDescription
iterableRequiredAny iterable, with one or more items to compare
keyOptionalA function to specify the comparison criteria. Default value is None.
defaultOptionalA 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.

danger

If the iterable is empty, a ValueError is raised.

To avoid such exception, add default parameter. The default parameter specifies a value to return if the provided iterable is empty.

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

aaaa

Example 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

for

Example 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: 10

output

10

Example 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: 2

output

2

For 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: Java

output

Java

Example 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}

# the smallest key
key1 = min(square)
print("The smallest key:", key1) # Output: -3

# the key whose value is the smallest
key2 = min(square, key = lambda k: square[k])

print("The key with the smallest value:", key2) # Output: -1

# getting the smallest value
print("The smallest value:", square[key2]) # Output: 1

output

The smallest key: -3
The key with the smallest value: -1
The smallest value: 1

Observe that:

  • The second min() function use the lambda function passed to the key parameter.

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 sequence

To 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

0

Example 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)