Python min() Function Explained
In Python, the min() function is a built-in function used to find the smallest element in a given iterable object. It can accept one or more arguments, as well as an optional keyword argument to specify a comparison rule.
Below are some common usages of the min() function:
Find the smallest element in an iterable object.
numbers = [5, 2, 8, 1, 6]
min_number = min(numbers)
print(min_number) # 输出:1
Compare multiple numerical values and return the smallest one.
min_value = min(10, 20, 5, 15)
print(min_value) # 输出:5
3. Specify the comparison rule using keyword arguments.
students = [
{'name': 'Alice', 'age': 20},
{'name': 'Bob', 'age': 18},
{'name': 'Charlie', 'age': 22}
]
youngest_student = min(students, key=lambda x: x['age'])
print(youngest_student) # 输出:{'name': 'Bob', 'age': 18}
Here are some common uses of the min() function, which is very convenient for finding the smallest element in an iterable object, whether it be numbers, strings, or custom objects.