Related Tags

python
maximum
minimum
list
communitycreator

# How to find max and min from a list

Manzar Iqbal Malik

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
Function to find maximum number of a list.
# 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
Function to find minimum number of a list.

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))
Validate the max and min functions.

Note: The functions will generate an error for empty lists.

RELATED TAGS

python
maximum
minimum
list
communitycreator

CONTRIBUTOR

Manzar Iqbal Malik
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time