Trusted answers to developer questions

How to find max and min from a list

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

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 number
def max_check(x):
max_val = x[0]
for check in x:
if check > max_val:
max_val = check
return max_val
# Pass a list to this function to check for minimum number
def min_check(x):
min_val = x[0]
for check in x:
if check < min_val:
min_val = check
return 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 number
def max_check(x):
max_val = x[0]
for check in x:
if check > max_val:
max_val = check
return max_val
# Pass a list to this function to check for minimum number
def min_check(x):
min_val = x[0]
for check in x:
if check < min_val:
min_val = check
return min_val
#List
my_list = [2, 6, 8, 14, 3, 77, 63]
#Printing Values
print("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.

RELATED TAGS

python
maximum
minimum
list
Did you find this helpful?