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.
Python code
21 linesdef 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
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
- Return the peak values instead of indices by adding `numbers[i]` to a separate list
- 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
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.