How to Find the Maximum Value in a Python List

This code defines a function that finds the largest number in a list by iterating through it, returning None for an empty list, and demonstrates it on a sample list.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 15 views 0 copies

Python code

13 lines
Python 3.9+
def find_max(numbers):
    if not numbers:
        return None
    max_value = numbers[0]
    for num in numbers[1:]:
        if num > max_value:
            max_value = num
    return max_value

if __name__ == "__main__":
    sample_list = [3, 7, 2, 9, 1, 9]
    result = find_max(sample_list)
    print(f"Maximum value: {result}")

Output

stdout
Maximum value: 9

How it works

The function find_max initializes max_value to the first element of the list, then iterates over the remaining elements. For each number, if it is greater than the current max_value, the variable is updated. If the list is empty, the function returns None to avoid an indexing error. This manual approach gives you control over the iteration and is a good exercise for understanding loops and comparisons.

Common mistakes

  • Forgetting to handle an empty list, causing an IndexError when accessing numbers[0]
  • Starting max_value at 0 instead of the first element, which fails for lists with all negative numbers
  • Using >= instead of >, which would return the first occurrence of the maximum but still works correctly

Variations

  1. Use the built-in `max(numbers)` function for a concise one-liner
  2. Sort the list and take the last element, but this is less efficient for large lists

Real-world use cases

  • Finding the highest score in a game leaderboard from a list of player scores.
  • Determining the maximum temperature recorded from a sensor's list of readings.
  • Identifying the most expensive item in a shopping cart list for price calculations.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.