Table of Contents
Introduction
In previous section we understood to find the largest number. Now, we will understand the different methods to find the smallest number in the list.
Program
list = [11, 2, 17, 10, 12, 3, 4] # Using loop def smallest(list): min = list[0] for i in list: if min > i: min = i return min print("Smallest number using loop: ",smallest(list)) # Using sort() list.sort() print("Smallest number using sort(): ",list[0]) # Using min() smallest_result = min(list) print("Smallest number using min(): ",smallest_result)
Output
Explanation
We have used loop, sort() and min() to find the smallest number in the list. We have assigned the first element as the min. Each time the min is greater than the value of list, the value is exchanged. The min value is returned when all the elements are greater than min.
By using sort(), we have sorted the list in ascending order and taken the element at index 0 (smallest).
The min() function directly finds the minimum number in the list and returns the result.
0 Comments