3 Easy Methods to Find the Smallest Number in Python

SMALLEST NUMBER IN PYTHON

Hello there! This article is for beginners who wish to understand the basic code for finding the smallest number in Python. So let’s begin.

How to Find the Smallest Number in Python?

We aim to find the smallest number in Python of all the numbers given in a list.

Say if the list is: [32, 54, 67, 21]

The output should be: 21

In this article, we will understand 3 different methods to do this.

1. Using Python min()

Min() is a built-in function in python that takes a list as an argument and returns the smallest number in the list. An example is given below-

#declaring a list
list1 = [-1, 65, 49, 13, -27] 
print ("list = ", list1)

#finding smallest number
s_num = min (list1)
print ("The smallest number in the given list is ", s_num)

Output:

list = [-1, 65, 49, 13, -27]
The smallest number in the given list is  -27

This is one of the simplest methods to find the smallest number. All you need to do is to pass the list to min() as an argument.

2. Using Python sort()

Sort() is another inbuilt method in python that doesn’t return the smallest number of the list. Instead, it sorts the list in ascending order.

So by sorting the list, we can access the first element of the list using indexing and that will be the smallest number in that list. Let’s see the code:

#declaring a list
list1 = [17, 53, 46, 8, 71]
print ("list = ", list1)

#sorting the list
list1.sort ()

#printing smallest number
print ("The smallest number in the given list is ", list1[0])

Output:

list =  [17, 53, 46, 8, 71]
The smallest number in the given list is 8

3. Using the ‘for’ loop

ls1 = []
total_ele = int (input (" How many elements you want to enter? "))

#getting list from the user
for i in range (total_ele):
  n =int (input ("Enter a number:"))
  ls1.append(n)
print (ls1)
min = ls1[0]

#finding smallest number
for i in range (len (ls1)):
  if ls1[i] < min:
    min = ls1[i]
print ("The smallest element is ", min)

In the above code, we are using two for loops, one for getting the elements of the list from the user and the second one for finding the smallest number from the list.

After getting the elements from the user, we define the first element of the list (at 0 index) as the smallest number (min). Then with the for loop, we compare each element of the list to the min and if any element is smaller than min, it becomes the new min.

This is how we get the smallest number from the user-given list.

The output for the above code is:

How many elements you want to enter? 4
Enter a number: 15
Enter a number: 47
Enter a number: 23
Enter a number: 6
[15, 47, 23, 6]
The smallest number is  6

Conclusion

So, these were some methods to find the smallest number from the given list in python. Hope you understood this! Feel free to ask questions below, if any. Thank you! 🙂