min() Function in Python

Python min() Function

The min() function in Python is used to find the smallest item in an iterable or among multiple arguments. It takes either an iterable (such as a list, tuple, or set) or multiple arguments and returns the minimum value.

Here's the general syntax of the min() function:

min(iterable, *args, key=None, default=None)

The parameters are as follows:

  • iterable (required): An iterable object like a list, tuple, or set, or any other object that can be iterated.
  • *args (optional): Additional iterables or values that you want to compare.
  • key (optional): A function that defines the sorting criterion. It takes one argument and returns a value to compare. The default is None, which means the elements are compared directly.
  • default (optional): A value to return if the iterable is empty.

Here are a few examples to illustrate the usage of the min() function:

numbers = [5, 2, 8, 1, 9]
smallest = min(numbers)
print(smallest)  # Output: 1

strings = ['apple', 'banana', 'cherry', 'date']
shortest = min(strings, key=len)
print(shortest)  # Output: date

a = 10
b = 20
c = 5
smallest_value = min(a, b, c)
print(smallest_value)  # Output: 5

In the first example, min(numbers) returns the smallest number from the list. In the second example, min(strings, key=len) compares the strings based on their lengths and returns the shortest string. In the third example, min(a, b, c) compares three values and returns the smallest one.

Note that if you pass an empty iterable to min(), it will raise a ValueError by default. You can use the default parameter to specify a default value to return instead of raising an error.

empty_list = []
smallest_value = min(empty_list, default=0)
print(smallest_value)  # Output: 0

In this case, min(empty_list, default=0) returns 0 because the list is empty.