# Using min() function
numbers = [40, 30, 50, 20, 90, 60]
result = min(numbers)
print(result)
# -> 20
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.
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
0 Comments