Python Program to Find Smallest Number in a List
Given a list of numbers, the task is to find the smallest element in that list.
For example:
li= [8, 3, 1, 9, 5] -> Smallest number = 1
li = [10, 25, 7, 30, 2] -> Smallest number = 2
Let’s explore different methods to find smallest number in a list.
Using min()
min() function takes an iterable (like a list, tuple etc.) and returns the smallest value.
a = [8, 3, 5, 1, 9, 12]
res = min(a)
print(res)
Output
1
Using for Loop
We can also find the smallest number in a list 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]
res = a[0]
for val in a:
if val < res:
res = val
print(res)
Output
1
Explanation:
- Start by assuming the first element is the smallest (res = a[0]).
- Compare each element with res.
- If a smaller value is found, update res.
- After the loop ends, res holds the smallest number.
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()
res = a[0]
print(res)
Output
1
Explanation:
- sort() arranges the list in ascending order.
- The first element (a[0]) becomes the smallest value.