search

What is the use of the "min" function in Python?

In Python, the min() function is a built-in function used to determine the smallest item from a collection of values or an iterable. It returns the minimum value based on a specified criteria.

The general syntax of the min() function is as follows:

min(iterable, *iterables, key=None, default=None)
  • iterable: The input collection or iterable from which the minimum value will be determined.
  • *iterables (optional): Additional iterables that can be provided to compare values from multiple collections simultaneously.
  • key (optional): A function that is used to extract a comparison key from each element before determining the minimum value. It is often used for custom comparisons or when comparing complex objects.
  • default (optional): A default value to be returned if the iterable is empty. If not provided, a ValueError will be raised when the iterable is empty.

Here's an example to demonstrate the usage of the min() function:

numbers = [3, 1, 4, 2, 5]
minimum = min(numbers)

print(minimum)  # Output: 1

In this example, the min() function is used to determine the smallest value from the numbers list, which is 1. The minimum value is then assigned to the minimum variable.

The min() function can also be used with multiple iterables or a combination of values and iterables:

numbers = [3, 1, 4, 2, 5]
letters = ['B', 'A', 'C']
combined = min(numbers, letters)

print(combined)  # Output: 1

In this example, the min() function compares elements from both the numbers list and the letters list. It determines the minimum value based on their natural order. In this case, since the minimum value is found in the numbers list, it returns 1.

The min() function can also accept a key argument to specify a custom comparison key. The key argument should be a function that takes an element as input and returns a value based on which the comparison is made.

students = [
    {'name': 'Alice', 'age': 20},
    {'name': 'Bob', 'age': 18},
    {'name': 'Charlie', 'age': 22}
]

youngest_student = min(students, key=lambda student: student['age'])

print(youngest_student)  # Output: {'name': 'Bob', 'age': 18}

In this example, the min() function uses the key argument with a lambda function to extract the 'age' key from each dictionary in the students list. It then determines the student with the minimum age and returns the corresponding dictionary.

The min() function is useful when you need to find the minimum value from a collection or perform custom comparisons based on a specific key or criterion. It provides a simple and efficient way to determine the smallest item from a set of values.

Related Questions You Might Be Interested