- 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 โ Replacing by Greatest Neighbors in a List
When it is required to replace the elements of the list by greatest neighbours, a simple iteration along with the ‘if’ and ‘else’ condition is used.
Example
Below is a demonstration of the same
my_list = [41, 25, 24, 45, 86, 37, 18, 99] print("The list is :") print(my_list) for index in range(1, len(my_list) - 1): my_list[index] = my_list[index - 1] if my_list[index - 1] > my_list[index + 1] else my_list[index + 1] print("The resultant list is :") print(my_list)
Output
The list is : [41, 25, 24, 45, 86, 37, 18, 99] The resultant list is : [41, 41, 45, 86, 86, 86, 99, 99]
Explanation
A list of integers is defined and is displayed on the console.
The list is iterated over and the specific index of the elements are accessed.
If the previous index is greater than the consecutive second index, the previous index is replaced with current index.
This list is displayed as output on the console.
Advertisements