Python: Get the smallest number from a list
Get Smallest Number in List
Write a Python program to get the smallest number from a list.
Visual Presentation:
Sample Solution:
Python Code:
# Define a function called smallest_num_in_list that takes a list 'list' as input
def smallest_num_in_list(list):
# Initialize a variable 'min' with the first element of the input list as the initial minimum
min = list[0]
# Iterate through each element 'a' in the input list 'list'
for a in list:
# Check if the current element 'a' is smaller than the current minimum 'min'
if a < min:
# If 'a' is smaller, update the minimum 'min' to 'a'
min = a
# Return the final minimum value in the list
return min
# Call the smallest_num_in_list function with the list [1, 2, -8, 0] as input and print the result
print(smallest_num_in_list([1, 2, -8, 0]))
Sample Output:
-8
Explanation:
In the above exercise -
def smallest_num_in_list( list ): -> This code defines a function “smallest_num_in_list()” that takes a single argument list. This function will be used to find the smallest number in the list.
min = list[ 0 ] -> We assume the list is not empty. This line initializes a variable called 'min' to the first element of the list.
for a in list: -> This line starts a loop that will iterate over each element in the list, one at a time. The loop variable 'a' will take on the value of each element in the list during each iteration of the loop.
if a < min: min = a
The above line compares the current element 'a' to the current smallest min. If 'a' is less than 'min', 'min' is updated to equal 'a'. After iterating through the entire list, ‘min’ will hold the value of the smallest number in the list.
return min -> This line returns the final value of the 'min' variable after the loop has finished.
print(smallest_num_in_list([1, 2, -8, 0])) -> This line calls the 'smallest_num_in_list()' function and passes in the list [1, 2, -8, 0]. Finally print() function prints the resulting smallest value.
Flowchart:
Python Code Editor:
Previous: Write a Python program to get the largest number from a list.
Next: Write a Python program to count the number of strings where the string length is 2 or more and the first and last character are same from a given list of strings.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics