How to Find Local Maxima in a Python List

Return the indices of all local maxima in a numeric list, where a peak is an element greater than both its immediate neighbors.

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

Python code

21 lines
Python 3.9+
def find_peaks(numbers):
    """
    Return the indices of local maxima in a numeric list.
    A local maximum is an element greater than both its neighbors.
    """
    if len(numbers) < 3:
        return []
    
    peaks = []
    for i in range(1, len(numbers) - 1):
        if numbers[i] > numbers[i - 1] and numbers[i] > numbers[i + 1]:
            peaks.append(i)
    return peaks


if __name__ == "__main__":
    data = [1, 3, 7, 1, 2, 6, 3, 2, 1, 5, 1]
    peak_indices = find_peaks(data)
    print(f"List: {data}")
    print(f"Peak indices: {peak_indices}")
    print(f"Peak values: {[data[i] for i in peak_indices]}")

Output

stdout
List: [1, 3, 7, 1, 2, 6, 3, 2, 1, 5, 1]
Peak indices: [2, 5, 9]
Peak values: [7, 6, 5]

How it works

This function scans each interior element (skipping the first and last since they lack two neighbors) and checks whether it's strictly greater than both adjacent values. The loop uses range(1, len(numbers) - 1) to visit only valid peak candidates. Each qualifying index gets appended to the results list, preserving left-to-right order. A list shorter than three elements returns an empty list because no local maximum can exist. The algorithm is O(n) — it inspects every element once and requires no extra memory beyond the output list.

Common mistakes

  • Forgetting that first and last elements can't be local maxima and trying to check them anyway
  • Using >= instead of > so plateaus (equal neighbors) get wrongly counted as peaks
  • Not handling lists shorter than 3 elements, which causes an IndexError
  • Returning values instead of indices when the problem asks for positions

Variations

  1. Return the peak values instead of indices by adding `numbers[i]` to a separate list
  2. Use a list comprehension: `[i for i in range(1, len(nums)-1) if nums[i] > nums[i-1] and nums[i] > nums[i+1]]`

Real-world use cases

  • Finding price spikes in a time series of sensor readings to trigger anomaly alerts.
  • Locating signal peaks in audio or waveform data for beat or note detection.
  • Identifying demand peaks in daily traffic logs to scale server capacity proactively.

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.