Open In App

Python program to find smallest number in a list

Last Updated : 23 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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.

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).

Frequently Asked Questions on Finding Smallest Number in List

What is min() function in Python?

The min() function is a built-in Python function that returns the smallest item in an iterable or the smallest of two or more arguments. It works with lists, tuples, and other data structures.

Which is the best way to find the smallest number in Python?

The best method depends on your situation. If you are looking for simplicity and readability, use min(). For an educational purpose, using a for loop may help you understand how comparisons work.

Can I use NumPy to find the smallest number?

Yes, you can use the NumPy library to find the smallest number using “np.min(list_name)”




Next Article

Similar Reads

three90RightbarBannerImg