![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Python Program – Print the count of either peaks or valleys from a list
When it is required to print the count of either peaks or valleys from a list, a simple iteration and a specific condition is placed.
Below is a demonstration of the same −
Example
my_list = [11,12, 24, 12, 36, 17, 28, 63] print("The list is :") print(my_list) my_result = 0 for index in range(1, len(my_list) - 1): if my_list[index + 1] > my_list[index] < my_list[index - 1] or my_list[index + 1] < my_list[index] > my_list[index - 1]: my_result += 1 print("The result is :") print(my_result)
Output
The list is : [11, 12, 24, 12, 36, 17, 28, 63] The result is : 4
Explanation
A list is defined and is displayed on the console.
An integer variable is initialized to 0.
The list is iterated over, and the consecutive indices are checked to see if they are less than or greater than each other.
If so, the integer is incremented by 1.
This is displayed as output on the console.
Advertisements