Finding the maximum and minimum values in a list is pretty easy because of the built-in max
and min
functions provided by Python. However, you may be wondering what the logic behind these functions is. Let me explain it with a couple of code snippets.
# Pass a list to this function to check for maximum numberdef max_check(x):max_val = x[0]for check in x:if check > max_val:max_val = checkreturn max_val
# Pass a list to this function to check for minimum numberdef min_check(x):min_val = x[0]for check in x:if check < min_val:min_val = checkreturn min_val
To validate our above defined functions, let’s pass a list to them.
# Pass a list to this function to check for maximum numberdef max_check(x):max_val = x[0]for check in x:if check > max_val:max_val = checkreturn max_val# Pass a list to this function to check for minimum numberdef min_check(x):min_val = x[0]for check in x:if check < min_val:min_val = checkreturn min_val#Listmy_list = [2, 6, 8, 14, 3, 77, 63]#Printing Valuesprint("Maximum of the list", max_check(my_list))print("Minimum of the list", min_check(my_list))
Note: The functions will generate an error for empty lists.