Find the smallest number in a python list
In this post, we are going to show you how to find the smallest number in a python list. It’s a very simple but useful task. We will go through the code, its running process, and the output result.
# Using min() function
numbers = [40, 30, 50, 20, 90, 60]
result = min(numbers)
print(result)
# -> 20
Output
We can get the smallest number from a python list using min() and sort() methods. We are going to explain both methods here. In the above code snippet, we have used the min() function to find the smallest number in a list.
1. We have defined a list(numbers) that contains multiple int values.
2. We are using the min() function and passing our list to this method. This will return the lowest integer value from the list.
Get the lowest number using sort() method
We can also get the smallest number using the sort() method. First, sort the list using List.sort() method and then return the very first element of the list. We can understand this using below example.
numbers = [40, 30, 50, 20, 90, 60]
numbers.sort()
print(numbers[0])
# -> 20
Note that all the values of the list must be integer types or it will throw an exception. That means if we run the below code in python.
numbers = [40, 30, 50, 20, "30", 60]
print(min(numbers))
The above code will throw an error.
Traceback (most recent call last):
File "main.py", line 5, in <module>
print(min(numbers))
TypeError: '<' not supported between instances of 'str' and 'int'
So it is necessary to convert all values of the list to integer type values.
Convert all string values in a list to integers using python
- Find the largest number in a list Python
- Find all indexes of an item in a list using python
- Find the most repeated item from a list in Python
- Find minimum value from a List in Python
- Get the second largest number from a list in Python
- Python code to check if a given number exists in a list
- Python String.find() function