Skip to main content

How to find the maximum and minimum values in a list

How to find the maximum and minimum values in a list.

Here is a detailed step-by-step tutorial on how to find the maximum and minimum values in a list.

Step 1: Understand the Problem

To find the maximum and minimum values in a list, we need to iterate over each element in the list and compare it with the current maximum and minimum values.

Step 2: Initialize Variables

Before we start iterating over the list, we need to initialize two variables to keep track of the maximum and minimum values. Let's call these variables max_value and min_value. We can set both of them initially to the first element of the list.

max_value = my_list[0]
min_value = my_list[0]

Step 3: Iterate over the List

Next, we need to iterate over each element in the list. We can use a for loop for this. Let's assume the list is called my_list.

for num in my_list:
# Compare the current element with the maximum value
if num > max_value:
max_value = num

# Compare the current element with the minimum value
if num < min_value:
min_value = num

In each iteration, we compare the current element with the current maximum and minimum values. If the current element is greater than the current maximum value, we update max_value. Similarly, if the current element is smaller than the current minimum value, we update min_value.

Step 4: Print the Maximum and Minimum Values

After the loop finishes, we can print the maximum and minimum values.

print("Maximum value:", max_value)
print("Minimum value:", min_value)

Complete Example

Here's a complete example that puts all the steps together:

my_list = [5, 2, 9, 1, 7]

max_value = my_list[0]
min_value = my_list[0]

for num in my_list:
if num > max_value:
max_value = num

if num < min_value:
min_value = num

print("Maximum value:", max_value)
print("Minimum value:", min_value)

Output:

Maximum value: 9
Minimum value: 1

That's it! You now know how to find the maximum and minimum values in a list using Python.