- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Program to find local peak element indices from a list of numbers in Python

Suppose we have a list of numbers called nums whose length is at least 2. We have to find the index of every peak in the list. The list is sorted in ascending order. An index i is a peak when −

nums[i] > nums[i + 1] when i = 0

nums[i] > nums[i - 1] when i = n - 1

nums[i - 1] < nums[i] > nums[i + 1] else

So, if the input is like nums = [5, 6, 7, 6, 9], then the output will be [2, 4], as the element at index 2 is 7 which is larger than two neighbors, and item at index 4 is 9, this is larger than its left item.

To solve this, we will follow these steps −

ans := a new list

n := size of nums

if n is same as 1, then

return ans

for each index i and number num in nums, do

if i > 0 and i < n - 1, then

if nums[i - 1] < num > nums[i + 1], then

insert i at the end of ans

if i is same as 0, then

if num > nums[i + 1], then

insert i at the end of ans

if i is same as n - 1, then

if num > nums[i - 1], then

insert i at the end of ans

return ans

## Example

Let us see the following implementation to get better understanding

def solve(nums): ans = [] n = len(nums) if n == 1: return ans for i, num in enumerate(nums): if i > 0 and i < n - 1: if nums[i - 1] < num > nums[i + 1]: ans.append(i) if i == 0: if num > nums[i + 1]: ans.append(i) if i == n - 1: if num > nums[i - 1]: ans.append(i) return ans nums = [5, 6, 7, 6, 9] print(solve(nums))

## Input

[5, 6, 7, 6, 9]

## Output

[2, 4]

- Related Articles
- Program to find indices or local peaks in Python
- Find Peak Element in Python
- Find a peak element in Linked List in C++
- Python program to get the indices of each element of one list in another list
- Program to find missing numbers from two list of numbers in Python
- Find a peak element in C++
- Program to find number of arithmetic sequences from a list of numbers in Python?
- Program to find number of arithmetic subsequences from a list of numbers in Python?
- Python Program to get indices of sign change in a list
- Find elements of a list by indices in Python
- Python - Ways to find indices of value in list
- Program to find largest distance pair from two list of numbers in Python
- Python program to remove elements at Indices in List
- Program to find length of longest sign alternating subsequence from a list of numbers in Python
- Program to find duplicate element from n+1 numbers ranging from 1 to n in Python