Python 3 – Number min() Method
In Python 3, the min()
method can be used to find the minimum value among two or more numeric values. The method returns the smallest number of the given arguments. This method can only compare values of the same type, meaning it can’t be used to compare a string to a number.
Syntax:
min(num1, num2, num3…)
Example
We can use the min()
method to find the smallest value among two integers:
x = 6
y = 3
print(min(x,y))
Output: 3
The min()
Method with Lists
We can also take the min()
method to work with lists. It returns the smallest item of a non-empty iterable object. Consider the following example:
lst = [3, 5, 1, 8, 2]
print(min(lst))
Output: 1
Real-life examples
There are many ways we can make use of the min()
method in our code, here are some examples:
Smallest item in a list:
fruits = ['banana', 'apple', 'strawberry', 'kiwi']
print(min(fruits))
Output: apple
Smallest Number from Given Input
numbers = []
for i in range(5):
num = int(input())
numbers.append(num)
print(min(numbers))
We take input from the user for 5 times and append each value to a list. Finally, we print the minimum value.
Smallest Number from a File
Let’s say that we have a file named numbers.txt
which contains some numbers. We need to find the minimum number from that file.
Here’s how we can do it:
with open('numbers.txt') as f:
numbers = [int(line) for line in f]
print(min(numbers))
We open the file and read each line, then we store all the numbers in a list. Finally, we use the min()
method to find the smallest number.
Find the Minimum Value from Dictionary
marks = {'A': 70, 'B': 85, 'C': 60, 'D': 75}
print(min(marks.values()))
Output: 60
Conclusion
In this article, we learned how to use the min()
method in Python 3 to find the minimum value among two or more numbers. We also saw how the method can be used with lists, files, and dictionaries. The method can be an important tool when it comes to working with numbers in Python, and understanding how it works can help you write more effective code.