Finding the Smallest Number in a List Using Python
In this tutorial, you’ll learn how to find and print the smallest number in a list using python. This is a common programming problem which can be useful for various tasks like finding minimum values, …
In this tutorial, you’ll learn how to find and print the smallest number in a list using python. This is a common programming problem which can be useful for various tasks like finding minimum values, etc.
Finding the Smallest Number in a List
In Python, one of the most commonly used data types is the list. Lists are mutable and can store any type of elements. Sometimes, we need to find the smallest element from that list. For this, python has a built-in method min() that returns the smallest item from an iterable or the smallest of two or more arguments.
Let’s see how to print the smallest number in a list using Python:
- Create a List:
numbers = [4, 2, 9, 7, 5]
- Use min() function:
min_number = min(numbers)
print("The smallest number in the list is ", min_number)
This will print “The smallest number in the list is 2”. If you have two numbers with same minimum value, this method will return only one of them.
You can also use the min() function if you want to get all the minimum elements. It will return a list of minimum elements:
min_elements = [number for number in numbers if number == min(numbers)]
print("The smallest numbers are", min_elements)
This will print “The smallest numbers are [2]”.
Remember, this method throws an error if the list is empty. So before using this method, it’s good to check whether the list is not empty or not.