- Trending Categories
- Data Structure
- Operating System
- C Programming
- 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.
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)
The list is : [41, 25, 24, 45, 86, 37, 18, 99] The resultant list is : [41, 41, 45, 86, 86, 86, 99, 99]
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.
- How to find the greatest number in a list of numbers in Python?
- Greatest Sum Divisible by Three in C++
- Replacing multiple occurrence by a single occurrence in SAP HANA
- Greatest common divisors in Python
- Program to find latest valid time by replacing hidden digits in Python
- Program to reverse a list by list slicing in Python
- List expansion by K in Python
- Check if a string can be converted to another string by replacing vowels and consonants in Python
- Find elements of a list by indices in Python
- Python – Sort by Units Digit in a List
- Greatest Common Divisor of Strings in Python