Home Resource Centre Python min() Function | Syntax, Exceptions & More (+Code Examples)

Python min() Function | Syntax, Exceptions & More (+Code Examples)

The Python min() function is a versatile tool for identifying the smallest element within an iterable object, such as a list, tuple, or string. It simplifies the process of finding the minimum value, thus eliminating the need to manually iterate through the elements and compare them.

In this article, we will understand the workings of the Python min() function and explore its syntax, parameters, and various use cases. We'll also provide code examples to illustrate how this function can be used in different scenarios, helping you utilize its power to enhance your Python programming skills.

What Is Python min() Function?

The min() function in Python is a built-in function that returns the smallest input value. It can take multiple arguments or a single iterable argument and is widely used in various applications.

Syntax Of Python min() Function:

There are two ways in which we can declare the min() function in Python:

1. Syntax With Multiple Arguments:

min(a, b, c, …, key=func)

Here:

  • a, b, c, … are the individual arguments that we pass to the min() function for comparison.
  • The key parameter is optional. It allows us to pass a function (func) that defines a custom sorting or comparison criterion.

For Example:

result = min(10, 5, 20, key=lambda x: x)
print(result) # Output: 5

2. Syntax With Iterables: 

min(iterable, key=func)

Here, 

  • iterable is a sequence (like a list, tuple, string, dictionary, etc.) from which we find the minimum value.
  • key=func is an optional parameter where func is a single argument function that defines the criteria for comparison.
  • If no key function is provided, the Python min() function will directly compare the elements of the iterable.

For Example:

numbers = [-10, -5, 3, -1]
min_abs_value = min(numbers, key=abs)
print(min_abs_value) # Output: -1

Return Values Of Python min() Function

  • The min() function returns the smallest value among the input values.
  • If an additional iterable is provided, it returns the smallest item from that iterable.

Exceptions Of Python min() Function 

The Python min() function can raise exceptions under certain conditions:

  • ValueError: This exception occurs if no arguments are passed to the function. For example-

min() # Raises ValueError: min() arg is an empty sequence

  • TypeError: This exception can be raised if the elements being compared are of different and incompatible types. For example-

min(1, 'two') # Raises TypeError: '<' not supported between instances of 'str' and 'int'

Let's explore some practical applications of the min() function in Python programming through different  examples:

Python min() To Find The Smallest Item In The List Of Integers 

In this example, we will use the Python min() function to find the smallest number in a list of integers. The process involves defining a list, applying the minimum function, and printing the result.

Code Example: 

Output: 

The smallest number in the list is: 5

Explanation: 

In the above code example-

  1. We start by defining an integer list named numbers containing five integer values.
  2. Next, we call the min() function with numbers as an argument, returning the smallest number in the list.
  3. Finally, we print the smallest number in the list using the print() function.

Python min() To Find The Smallest String In A List

In this example, we will use the Python min() function to find the smallest string element based on its length from a list of strings.

Code Example:

Output:

The smallest string in the list is: 'kiwi'

Explanation: 

In the above code example-

  1. We start by defining a list of strings called fruits, which contains four types of fruit: "banana," "apple," "kiwi," and "grape."
  2. Next, we use the min() function to find the smallest string based on its length.
  3. We specify the fruits list as the first argument and then use the key=len parameter (built-in len() function) to indicate that the comparison should be based on the length of each string.
  4. Now, the min() function will iterate through the fruits list and identify the string with the smallest length, storing the result in the variable smallest_string.
  5. Finally, we print the result using the print() function and f-string to format our output, clearly stating the shortest string in the list.

Python min() To Find Minimum Element In A Dictionary

In this example, we will use the min() function to find the key associated with the minimum value in a dictionary. This approach is useful for determining the key with the smallest associated value, such as a score, price, or any measurable quantity.

Code Example: 

Output: 

The student with the lowest score is: Chandra with a score of 78

Explanation: 

In the above code example-

  1. We begin by defining a dictionary called scores, which holds key-value pairs where each key is a student's name and the corresponding value is their score.
  2. To find the student with the lowest score, we will use the min() function.
  3. We first provide the scores dictionary as the first argument and use the key=scores.get parameter. This tells the function to compare the values associated with each key (the scores).
  4. Then, we use the min() function to evaluate the scores and identify the key (student's name) corresponding to the smallest value, storing this result in the variable lowest_score_name.
  5. Lastly, we print a message identifying the student with the lowest score and their name.

Python min() To Find Minimum Value In A Tuple Of Floating-Point Numbers

In this example, we will use the min() function to find the smallest floating-point number in a tuple. This approach is straightforward, as tuples are immutable sequences in Python, and the minimum function can directly take a tuple as an argument to find the minimum value.

Code Example:

Output: 

The minimum temperature recorded is: 97.5°F

Explanation: 

In the above code example-

  1. We start by defining a tuple named temperatures, which contains five floating-point numbers representing temperature readings.
  2. Next, we use the min() function, passing temperatures as the argument to find the minimum temperature in the tuple.
  3. The min() function automatically evaluates all the values in the tuple and identifies the smallest one, storing it in the variable min_temperature.
  4. Finally, we print the result to show the minimum temperature recorded and "°F" to indicate the Fahrenheit value.

Python min() To Find The Smallest Element Using the Lambda Function

In this example, we will use the min() function and a lambda function to find the smallest element from a list of numbers. The key lambda function allows us to customize the comparison criteria, which can be particularly useful for more complex objects or when you need to transform data during comparison.

Code Example:

Output: 

The smallest number in the list is: 3

Explanation: 

In the above code example-

  1. We start by defining a list named numbers that contains five integer values.
  2. Next, we use the min() function to find the smallest number in the list.
  3. We first pass a lambda function as the key argument, where lambda x: x simply returns each number itself for comparison. This is equivalent to finding the smallest element based on its own value.
  4. Then, we use the min() function to evaluate all the numbers in the list and identify the smallest one, storing this result in the variable smallest_number.
  5. Finally, we print the result using an f-string, indicating the smallest number in the list.

Conclusion

Python's min() function is a versatile and powerful tool for finding the smallest element from various data structures, such as lists, tuples, and dictionaries. By allowing the use of both multiple arguments and iterables, min() can be adapted to suit a wide range of scenarios. Whether you’re dealing with simple numbers or complex type of objects, the min() function simplifies finding the minimum value with minimal effort. Mastering this key function enhances your data handling capabilities in Python, making it an essential skill for efficient and clean code. 

Frequently Asked Questions

Q. Can the Python min() function handle strings?

Yes, the Python min() function can handle string-type values. When applied to a list of strings, it returns the lexicographically smallest string (i.e., alphabetically smallest).

Q. What is the use of the key parameter in the min() function?

The key parameter allows you to specify a custom function to determine the criteria for comparison. This is useful when working with complex data types or when comparing based on specific attributes.

Q. What does the min() function do in Python?

The Python min() function is a in-built function that returns the smallest item from a list of values or an iterable. It can also be customized to compare elements based on specific criteria using the key parameter.

Q. Can I use the Python min() function with dictionary values?

Yes, we can use the Python min() function with different dictionary values. By default, when applying min() to a dictionary, it compares the keys and returns the key with the smallest value.

However, we can also use the key function parameter to compare based on the dictionary's values instead of the keys. For instance, if we want to find the key corresponding to the smallest value, we can use min() with key=dict.get.

Q. What happens if we apply min() to an empty sequence?

If we apply the min() function to an empty sequence without providing a default value, Python will raise a ValueError. This happens because min() needs at least one minimum element to compare, and an empty sequence has none.

To avoid this error, we can use the default argument parameter, which specifies a fallback value in case the sequence is empty. For Example-

empty_list = []
result = min(empty_list, default="No values")
print(result) # Output: No values

In this case, "No values" will be returned if the sequence is empty.

Q. Can the Python min() function compare complex objects?

Yes, the Python min() function can compare complex objects if you provide a custom function using the key default parameter to define how to compare those custom objects. For example, you could compare objects based on an attribute like age or price.

Here are a few other topics that you might be interested in reading:

  1. Hello, World! Program In Python | 7 Easy Methods (With Examples)
  2. Python IDLE | The Ultimate Beginner's Guide With Images & Codes!
  3. Flask vs Django: Understand Which Python Framework You Should Choose
  4. Difference Between Java And Python Decoded
  5. Difference Between C and Python | C or Python - Which One Is Better?
Muskaan Mishra
Technical Content Editor

I’m a Computer Science graduate with a knack for creative ventures. Through content at Unstop, I am trying to simplify complex tech concepts and make them fun. When I’m not decoding tech jargon, you’ll find me indulging in great food and then burning it out at the gym.

TAGS
Python programming language Engineering Placements
Updated On: 15 Oct'24, 12:13 PM IST