Tutorial Study Image

Python min()

The built-in function min() helps to returns the smallest element in a given iterable. It can also possible to find the smallest element between two or more parameters.

# to find the smallest item in an iterable
min(iterable, *iterables, key, default)

# to find the smallest item between two or more objects
min(arg1, arg2, *args, key)

min() Parameters:

min() function with iterable has the following parameters.

min(iterable, *iterables, key, default)

Parameter Description Required / Optional
iterable  an iterable such as list, tuple, set, dictionary, etc. Required
*iterables any number of iterables; can be more than one Optional
key a key function where the iterables are passed and comparison is performed Optional
default  default value if the given iterable is empty Optional


min() function without iterable() have following parameters.

min(arg1, arg2, *args, key)

Parameter Description Required / Optional
arg1 an object; can be numbers, strings, etc Required
arg2 an object; can be numbers, strings, etc Required
*args any number of objects Optional
key  a key function where each argument is passed and comparison is performed Optional

min() Return Value

In case of passing an empty iterator, it will raise a ValueError exception for avoiding this, we can pass the default parameter.
And if we passing more than one iterators, then the smallest item from the given iterators is returned.

Input Return Value
Integer smallest integer
String the character with minimum Unicode value

Examples of min() method in Python

Example 1: Get the smallest item in a list

number = [13, 2, 8, 25, 10, 46]
smallest_number = min(number);

print("The smallest number is:", smallest_number)


The smallest number is: 2

Example 2: The smallest string in a list

languages = ["Python", "C Programming", "Java", "JavaScript"]
smallest_string = min(languages);

print("The smallest string is:", smallest_string)


The smallest string is: C Programming

Example 3:Find the min() in dictionaries

square = {2: 4, 3: 9, -1: 1, -2: 4}

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

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

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

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


TThe smallest key: -2
The key with the smallest value: -1
The smallest value: 1

Example 4:Find the minimum among the given numbers

result = min(4, -5, 23, 5)
print("The minimum number is:", result)


The minimum number is -5

Example 5:Find the min() of objects

class Data:
    id = 0

    def __init__(self, i):
        self.id = i

    def __str__(self):
        return 'Data[%s]' % self.id

def get_data_id(data):
    return data.id

# min() with objects and key argument
list_objects = [Data(1), Data(2), Data(-10)]

print(min(list_objects, key=get_data_id))