This article will go through the Python min Function and it’s uses complete with several examples.

The Python min function is used to find the ‘min’ value of a specific sequence or iteratable. By changing it’s parameters we can even change how this min value is calculated.

You might to have an ASCII table open with you while using this function. Here’s a link to one.


Syntax

min(sequence, default = "", key = func)
  • Sequence is the sequence of numbers/values through which the min function will be going through. Example; x = [5,6,7,8,3]
  • default holds the default value that will be printed if the sequence of values is empty. (Optional)
  • The key parameter can be assigned a function to change the way the min function calculates the min value. More on this below. (Optional)

Example 1:
>>> x = [5,7,-3,6,0]
>>> min(x)
-3

>>> x = [5,7,8,2,5]
>>> min(x)
2

>>> x = []
>>> min(x, default = 'empty')
'empty'

When comparing between strings, the min function by default, returns the one with the highest ASCII value. In comparing values in a dictionary, the min function returns the key with the highest value. Also, when you pass a single string through the min function, it will treat each individual character as a string of length 1, returning the highest value string.

Example 2:
>>> min('a','A')
'A'

>>> x = { 1: "Cat", 2: "Dog", 3: "Fox"}
>>> min(x)
1

>>> min("Hello")
'H'

Key Parameter

By changing the key value to the str.lower function, the min function will ignore any capitalization and treat all the strings like lowercase.

>>> min('a', 'b', 'D', 'A')
'A'

>>> min('a', 'b', 'D', key = str.lower)
'a'

By changing the key value to the len function, the min function will return the string which has the greatest length, instead of judging by ASCII standards.

>>> x = ["Grape", "Mango", "Fruit", "Strawberry"]
>>> min(x)
'Fruit'

>>> min(x, key = len)
'Grape'

This marks the end of the Python min Function. Any suggestions or contributions for CodersLegacy are more than welcome. Questions can be asked in the comment section below.

Here’s a link back to the main Python Built-in Functions page.

You might also want to see the max function which is the exact opposite to the min function.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments