Python program to find smallest number in a list
In this article, we will discuss various methods to find smallest number in a list. The simplest way to find the smallest number in a list is by using Python’s built-in min() function.
Using min()
The min() function takes an iterable (like a list, typle etc.) and returns the smallest value.
a = [8, 3, 5, 1, 9, 12]
# Find the smallest number
smallest = min(a)
print(smallest)
Output
1
Let us explore different methods to find smallest number in a list.
Table of Content
Using a For Loop
We can also find the smallest number in a list without using any built-in methods by using a loop (for loop). This method is useful for understanding how the comparison process works step by step.
a = [8, 3, 5, 1, 9, 12]
# Initialize "smallest" value with first element of list
smallest = a[0]
# Iterate through list to find smallest element
for val in a:
# If current value is smaller than current smallest value
if val < smallest:
# Update the smallest value
smallest = val
print(smallest)
Output
1
Using Sorting
Another way to find the smallest number in a list is by sorting it. Once sorted in ascending order, the smallest number will be at the beginning of the list.
a = [8, 3, 5, 1, 9, 12]
a.sort()
smallest = a[0]
print(smallest)
Output
1
Explanation:
- The sort() function sorts the list in ascending order.
- After sorting, the first element (a[0]) will be the smallest.
Note: This method is not recommended for finding the smallest number in a list. While it works but it is less efficient than using min() or a for loop. Sorting has a time complexity of O(n log n), whereas the other methods are O(n).