Python min() Function
Python min() function returns the smallest value from a set of values or the smallest item in an iterable passed as its parameter. It's useful when you need to quickly determine the minimum value from a group of numbers or objects. For example:
a = [23,25,65,21,98]
print(min(a))
b = ["banana", "apple", "mango", "kiwi"]
print(min(b))
Output
21 apple
Explanation:
- min(a) returns 21 because it's the smallest number in the list a.
- min(b) returns "apple" because Python compares strings in lexicographical order. Since "apple" starts with 'a', which comes before 'b' in "banana" and 'k' in "kiwi", it is considered the smallest.
Python min() function syntax
min(iterable, *[, key, default])
Parameters:
- iterable: A sequence like a list, tuple or string.
- key (optional): A function to determine how elements are compared.
- default (optional): Value to return if the iterable is empty.
Return Value: It returns the smallest item from the iterable. If key is used, it returns the smallest based on that function. If the iterable is empty and default is provided, it returns the default value.
Python min() examples
Example 1: In this example, min() uses key=len to find the shortest string by comparing lengths instead of alphabetical order.
a = ["Alice", "Bob", "Christina", "Dan"]
res = min(a, key=len)
print(res)
Output
Bob
Explanation: Here comparison is based on string lengths using key=len. Both "Bob" and "Dan" have three characters, but since "Bob" appears first in the list, it is returned.
Example 2: In this example, min() uses key=lambda x: x[1] to find the tuple with the smallest second element.
a = [(2, 3), (1, 5), (4, 1)]
res = min(a, key=lambda x: x[1])
print(res)
Output
(4, 1)
Explanation: key=lambda x: x[1] compares the tuples based on their second item. In the tuples (2, 3), (1, 5) and (4, 1), the second items are 3, 5 and 1, respectively. Since 1 is the smallest, the tuple (4, 1) is returned.
Example 3: In this example, min() uses the default parameter to return "No data" when the list is empty, avoiding a ValueError.
a = []
print(min(a, default="No data"))
Output
No data
Explanation: Without a default, min([]) raises a ValueError. Passing default="No data" provides a fallback, returning "No data" for an empty list.
Example 4: In this example, we are finding the minimum in a dictionary first by key, then by comparing values using the key parameter.
d = {'x': 50, 'y': 20, 'z': 70}
print(min(d))
# Key with the smallest value
min_key = min(d, key=lambda k: d[k])
print(min_key)
print(d[min_key])
Output
x y 20
Explanation: min(d) returns the smallest key alphabetically, while min(d, key=lambda k: d[k]) finds the key with the smallest value, 'y' and d[min_key] returns its value.
Hope this article helped you understand how to use the min() function and you can effectively use it in your projects.
Read More Python Built-in Functions
Similar Reads: