How do we use the min() function in Python?
The min() function
In Python, the min() function is used to check for the smallest item in an iterable, such as a list or tuple. It can also be used to return the smallest value between two values.
Syntax
The syntax of the min() function is:
min(n1, n2, n3, ...)
Or
min(iterable)
Return value
The min() function returns the smallest value.
Example 1
How to use the min() function in Python
# create a listscores = [50, 20, 9, 70, 45, 90, 5]# store resultresult = min(scores)# display resultprint(f"The lowest score : {result}")
Explanation
- Line 2: We create a list called
scores - Line 4: We use the
min()function to find the smallest item in the list. - Line 6: We display the result on the screen.
Example 2
How to use the min() function to find the smallest string in a given list
Note: The
min()function checks a list in alphabetical order.
# create a listcolor = ['Red','Orange', 'Blue', 'Pink']# store resultresult = min(color)# display resultprint(f"The lowest score : {result}")
Explanation
- Line 2: We create a list of strings called
color. - Line 4: We use the
min()function to find the smallest item in the list. - Line 6: We display the result on the screen.