Python min() function


(Sponsors) Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!


The min() function returns the smallest of the input values.

Its syntax is as follows:

Parameter       Description
iterable(required) An iterable object like string, list, tuple etc.
default(optional) The default value to return if the iterable is empty.
key(optional) It refers to the single argument function to customize the sort order. The function is applied to each item on the iterable.

or

Parameter    Description
a, b, c ...Items to compare
key(optional) It refers to the single argument function to customize the sort order. The function is applied on each of the items.

If min()  is called with an iterable, it returns the smallest item in it. If the iterable is empty then the default value is returned (assuming it is provided), otherwise a ValueError exception is raised.

If min() is called with multiple arguments, it returns the smallest one.

Let’s see some examples:

Example 1: Calling min() with an iterable

Example 2: Calling min() with multiple arguments

Trying to find largest value among the objects of different types causes an error.

Customing Sort Order

To customize the sort order we use the key named argument. It works exactly like the key named argument of the sorted()  function.

Here is an example where we use key argument to make the string comparision case-insentive.

The following is another example where we compare strings based on its length instead of their ASCII values.

There also exists a complementary function called max() which finds the largest of the input values.


Other Tutorials (Sponsors)

This site generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!


Leave a Reply

Your email address will not be published. Required fields are marked *