Python min() function: The Python min() function gives back the smallest item to a collection. It’s also used to get the smallest item that’s between two and more parameters. The min() function gets two arguments. The first one is elements collection & the second one is key & returns the least element a collection.
Python min() function with Examples
Syntax
Val1, val2, val3 are iterable objects which can include string, tuple, list, etc. Items to be compared.
Key (optional) refers to one argument function which customizes sort order. This function is applied to every item on iterable.
If the min() function is called using an iterable, it gives back the smallest item in it. If an iterable is empty the default value is reverted, else ValueError-exception is raised.
If the min() function is called using multiple arguments, it gives back the smallest one.
Find the minimum of 2 and above values
If you state two and above values, the value that will be returned will be the smallest.
When the values are strings, that string that has the smallest value in alphabetical order will be returned.
Remember that you have to state the minimum 2 values which compare. Else, the TypeError exception will be raised.
Finding the Minimum at an Iterable
When you state an Iterable (like list, set, tuple, etc.), the last item in the iterable will be returned.
When the iterable is void, ValueError will be raised.
To prevent this kind of an exception, you need to add a default parameter. This is the value to be returned when the given iterable is void.
Finding the Minimum with in-Built Function
With an optional key parameter, you will state custom comparison conditions to get the minimum value. Key parameter states a function that is to be executed on every iterable’s item before one makes comparisons.
For instance, using a strings list, stating key=len ( in-built len() function) gets the shortest string.
Finding the Minimum using Custom Function
One can pass in their custom function as a key function.
Remember the key function gets a single argument & gives back a key to utilize for comparison.
Get Minimum using lambda
A major function can be created using a lambda expression. This enables us to in-line function-definition.
Get the Minimum of Custom-Objects
Let us make students list (custom object) & find out who among them is the youngest.