Built with Tutify.io

    AIStudyLabs

    Python min() Function

    Python min() Function

    In Python, the min() function is used to get the smallest item from iterable objects or a sequence. The built-in min() function can take any number of arguments and return the smallest item among all the arguments. It can be used on lists, tuples, sets, and other iterable objects and returns the smallest item in the iterable object.

    In this article, I will explain the Python min() function and using its syntax, parameters, and usage how we can find the minimum element from a given list, tuples, sets, and dictionaries with examples.

    <a id="h-1-quick-examples-of-min-method"></a>

    1. Quick Examples of min() Method

    If you are in a hurry, below are some quick examples of the min() function.

    
    # Quick examples of min() method
    
    # Example 1: Find the smallest element in a string 
    # Using the min() function
    mystring =['Python','Spark','Java','Hadoop']
    min_value = min(mystring)
    
    # Example 2: Find the smallest element in the list
    mylist = [5, 3, 8, 15, 20]
    min_value = min(mylist)
    
    # Example 3: Find the smallest element in dictionaries 
    mydict = {'Python': 2000, 'Spark': 3000, 'Hadoop': 2500}
    min_value = min(mydict)
    
    # Example 4: Find the smallest value in dictionary
    min_value = min(mydict.items(), key=lambda x: x[1])
    
    # Example 5: Find the string with minimum length
    mystring =["Python","Spark","Java", "Hadoop"]
    min_value = min(mystring, key = len)
    
    # Example 6: Use min() function 
    # With multiple arguments
    a = 5
    b = 3
    c = 8
    min_val = min(a, b, c)
    
    # Example 7: Get minimum element of an empty list
    mylist =[]
    min_value = min(mylist)
    
    # Example 8: Aviod ValueError with
    # default value 0
    mylist =[]
    min_value = min(mylist, default=0)
    

    <a id="h-2-python-min-function"></a>

    2. Python min() Function

    Python min() function allows iterable objects as an argument and returns the lowest item among them. If the iterable object is the values of a string, comparison can be done alphabetically. Moreover, it allows two or more parameters and finds the smallest item among them.

    <a id="h-2-1-syntax-of-min-method"></a>

    2.1 Syntax of min() Method

    Following is the syntax of the min() method.

    
    # Syntax of min() function
    min(iterable, *iterables, key, default)
    

    <a id="h-2-2-parameter-of-min-method"></a>

    2.2 Parameter of min() method

    2.3 Return Value

    It returns the smallest element from an iterable, such as a list, tuple, or set.

    3. Usage of the min() Function with Iterables

    You can use the min() function over the iterable objects like lists, tuples, sets, or dictionaries to get the smallest value from a given iterable object.

    3.1 Get the Minimum String Using min() Function

    You can find the smallest element in a list of strings using the min() function. First, define a list of strings called mystring, and then you use the min() function to find the smallest element in the list. Finally, returns the smallest element in the list of strings based on alphabetical order.

    In this program, since the min() function is finding the smallest string based on alphabetical order, it returns "Hadoop" as the smallest element in the list.

    
    # Initialize list
    mystring =['Python','Spark','Java','Hadoop']
    print("Original list: ", mystring)
    
    # Find the smallest element in a string 
    # Using the min() function
    min_value = min(mystring)
    print("Get smallest element of string is: ", min_value)
    

    Yields below output.

    3.2 Get the Smallest Element in List Using the min() Function

    You can also use the min() function in Python to find the smallest element in a list. For example, you have a list called mylist that contains integers. You use the min() function to find the smallest element in the list, which is the number 3.

    
    # Initialize a list
    mylist = [5, 3, 8, 15, 20]
    print("Original list: ", mylist)
    
    # Find the smallest element in the list
    min_value = min(mylist)
    print("The smallest element in the list is:", min_value)
    

    Yields below output.

    3.3 Find the Smallest Element in Dictionaries

    You can also find the smallest element in dictionaries using the min() function. In dictionaries, you can find out the minimum value through the keys. If you want to find the key whose value is minimum, you can customize the key function of the max() function and get the minimum value of dict.

    For example, you first initialize a dictionary named mydict with three key-value pairs. The keys are strings ('Python', 'Spark', and 'Hadoop') and the values are integers (2000, 1000, and 2500, respectively). Then, use min() function on the dictionary mydict to find the smallest element in the dictionary, but this will return the smallest key in the dictionary, not the smallest value.

    
    # Initialize dictionary
    mydict = {'Python': 2000, 'Spark': 1000, 'Hadoop': 2500}
    print("Original dictionary: ", mydict)
    # Get minimum key in dict 
    # Using the min() function
    min_key1 = min(mydict)
    print("The maximum key of the dictionary: ", min_key1)
    
    # Get the key whose value is minimum
    min_key2 = min(mydict, key = lambda x: mydict[x])
    print("Get key whose value is minimum:", min_key2)
    print("Minimum value of dictionary:", mydict[min_key2])
    

    Yields below output.

    
    # Output:
    Original dictionary:  {'Python': 2000, 'Spark': 1000, 'Hadoop': 2500}
    The minimum key of the dictionary:  Hadoop
    Get key whose value is minimum: Spark
    Minimum value of dictionary: 1000
    

    <a id="h-4-find-the-string-with-minimum-length"></a>

    4. Find the String with Minimum Length

    You can also find the string with a minimum length using the min() function to find the smallest value in a variable called mystring. However, this will raise a TypeError because the min() function expects an iterable (such as a list or a dictionary), not a string. If you want to use the min() function to find the shortest string in a list of strings, you can use the key parameter.

    In the below example, the key parameter is set to the len() function, which returns the length of a string. The min() function then iterates over the strings list and returns the string with the smallest length according to the len() function.

    Related: In Python, you can get the maximum length value of the string.

    
    # Initialize list
    mystring =["Python","Spark","Java", "Hadoop"]
    print("Original dictionary: ", mystring)
    
    # Find the string with minimum length
    min_value = min(mystring, key = len)
    print("Get string with minimum length is: ", min_value)
    
    # Output:
    # Original dictionary:  ['Python', 'Spark', 'Java', 'Hadoop']
    # Get string with minimum length is:  Java
    

    <a id="h-5-use-min-function-with-multiple-arguments"></a>

    5. Use min() Function with Multiple Arguments

    You can also use the min() function with multiple arguments to find the smallest element among them. For example, you have three variables a, b, and c, which have the values 5, 3, and 8, respectively. you can use the min() function with these variables as arguments to find the smallest value among them, which is 3.

    
    # Use min() function 
    # With multiple arguments
    a = 5
    b = 3
    c = 8
    min_val = min(a, b, c)
    print("Get smallest element is: ",min_val)
    
    # Output:
    # Get smallest element is:  3
    

    <a id="h-6-get-valueerror-exception"></a>

    6. Get ValueError Exception

    When you find the minimum value of an empty list using the min() function, you will get ValueError as the message "min() arg is an empty sequence". This is because there is no minimum value to find in an empty list.

    
    # Initialize list
    mylist =[]
    
    # Get minimum value in empty list
    min_value = min(mylist)
    print(min_value)
    
    # Output:
    # Traceback (most recent call last):
    #  File "./prog.py", line 5, in <module>
    # ValueError: min() arg is an empty sequence
    

    7. Avoid ValueError with Default Value

    If you want to avoid this ValueError when using min() function over an empty list, you can set the default param as 0 along with the mylist. This function will return 0 instead of raising a ValueError.

    
    # Initialize list
    mylist =[]
    
    # Use min() function with
    # Default value 0
    min_value = min(mylist, default=0)
    print("Smallest number in the list is", min_value)
    
    # Output:
    # Smallest number in the list is: 0
    

    8. Conclusion

    In this article, I have explained the Python min() function and using its syntax, parameters, and usage how we can find the minimum element from an iterable object such as a list, tuples, sets, and dictionaries with multiple examples.

    Happy Learning !!

    <a id="h-related-links"></a>

    Related Links