Find Maximum Value in a List of Numbers in Python

Iterate through a list with a for loop to manually find and return the maximum numeric value.

Easy Python 3.6+ Aug 9, 2026 Lists & loops 16 views 0 copies

Python code

14 lines
Python 3.6+
def find_max(numbers):
    """Return the maximum value in a list of 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, 15, 9, 11]
    result = find_max(sample_list)
    print(f"Maximum value in {sample_list} is {result}")

Output

stdout
Maximum value in [3, 7, 2, 15, 9, 11] is 15

How it works

The function initializes max_value to the first element of the list, then loops through the remaining items. Each iteration compares the current element to max_value and updates it only when a larger number is found. This manual approach works for any iterable of comparable items and gracefully returns None for an empty list. For most cases, the built-in max() function is more concise and faster, but building it from scratch demonstrates basic loop and comparison logic.

Common mistakes

  • Starting `max_value` at 0, which breaks when all numbers are negative
  • Forgetting to handle an empty list, causing an IndexError
  • Using `<=` instead of `<` (works correctly but may do extra assignments)
  • Slicing the list with `[1:]` which creates a copy, inefficient for large lists

Variations

  1. Use the built-in `max()` function: `result = max(sample_list)`
  2. Use a list comprehension with `functools.reduce` for a functional approach

Real-world use cases

  • Scanning sensor readings to find the peak temperature in a batch before alerting.
  • Calculating the highest order value in a list of transaction amounts for reporting.
  • Determining the maximum score from a list of user metrics to set a leaderboard top entry.

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.