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.

Updated on: 20-Sep-2021

125 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements