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() 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 |
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 |
number = [13, 2, 8, 25, 10, 46]
smallest_number = min(number);
print("The smallest number is:", smallest_number)
Output
Output:
The smallest number is: 2
languages = ["Python", "C Programming", "Java", "JavaScript"]
smallest_string = min(languages);
print("The smallest string is:", smallest_string)
Output:
The smallest string is: C Programming
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
Output:
TThe smallest key: -2 The key with the smallest value: -1 The smallest value: 1
result = min(4, -5, 23, 5)
print("The minimum number is:", result)
Output:
The minimum number is -5
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))
Output:
Data[-10]