
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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.
- Related Articles
- How to find the greatest number in a list of numbers in Python?
- Program to find latest valid time by replacing hidden digits in Python
- Replacing multiple occurrence by a single occurrence in SAP HANA
- Program to reverse a list by list slicing in Python
- Greatest common divisors in Python
- Check if a string can be converted to another string by replacing vowels and consonants in Python
- Python – Sort by Units Digit in a List
- Greatest Sum Divisible by Three in C++
- Greatest number divisible by n within a bound in JavaScript
- Python – Sort a List by Factor count
- List expansion by K in Python
- Find elements of a list by indices in Python
- Count characters with same neighbors in C++
- Finding greatest digit by recursion - JavaScript
- Replacing strings with numbers in Python for Data Analysis

Advertisements