Whether you are writing a complex Python program or merely dabbling with code, there are plenty of times when you will need to find the smallest number in a list. The numbers could come from a variety of sources, such as data pulled from a database, user inputs, or even generated programmatically during runtime.
Regardless of how your data is sourced, Python provides multiple ways to locate the smallest number within the subroutine. This tutorial walks you through these methods with examples.
Step 1: Using Python’s Built-in min() Function
One of the easiest ways to find the smallest number in a list in Python is by using its built-in min() function. This function returns the smallest item of a list or the smallest of two or more arguments.
1 2 3 |
numbers = [12, 9, 21, 18, 27] minimumNumber = min(numbers) print('Minimum Number: ', minimumNumber) |
The usual use of the min() function, as seen above, will output:
Minimum Number: 9
Step 2: Using a For Loop
If, for any reason, you can’t or don’t want to use Python’s built-in functions, you can find the smallest number in a list by iterating over the list using a for loop.
1 2 3 4 5 6 7 8 |
numbers = [12, 9, 21, 18, 27] minimumNumber = numbers[0] for num in numbers: if num < minimumNumber: minimumNumber = num print('Minimum Number: ', minimumNumber) |
The above code initializes minimumNumber to the first number in the list and then iterates over the list. If it finds a number smaller than the current minimumNumber, it updates minimumNumber to that number. The final output will then be:
Minimum Number: 9
Complete Code:
For convenience, here are both methods combined in a single Python script:
1 2 3 4 5 6 7 8 9 10 11 12 |
# Method 1: Using min() function numbers = [12, 9, 21, 18, 27] minimumNumber = min(numbers) print('Minimum Number using min(): ', minimumNumber) # Method 2: Using for loop minimumNumber = numbers[0] for num in numbers: if num < minimumNumber: minimumNumber = num print('Minimum Number using for loop: ', minimumNumber) |
Conclusion
Python provides multiple efficient ways to find the smallest number in a list. The easiest and most performance-efficient method is to use Python’s built-in min() function. Alternatively, you can also use a for loop to manually iterate over the list and find the smallest number.
Remember, Python being a versatile language, gives you the flexibility to choose the best approach according to your specific needs and the context of the rest of your program.