Python - Remove non-increasing elements


When it is required to remove non-increasing elements, a simple iteration is used along with comparison of elements.

Example

Below is a demonstration of the same

my_list = [5,23, 45, 11, 45, 67, 89, 99, 10, 26, 7, 11]

print("The list is :")
print(my_list)

my_result = [my_list[0]]
for elem in my_list:

   if elem >= my_result[-1]:
      my_result.append(elem)

print("The result is :")
print(my_result)

Output

The list is :
[5, 23, 45, 11, 45, 67, 89, 99, 10, 26, 7, 11]
The result is :
[5, 5, 23, 45, 45, 67, 89, 99]

Explanation

  • A list is defined and is displayed on the console.

  • The first element of the list is assigned to another list.

  • The elements in the list are iterated over.

  • Every element is compared with the last element and checked to see if they are greater than or equal to the first element of the list.

  • If it is, then it is appended to the list.

  • This is the output that is displayed on the console.

Updated on: 21-Sep-2021

86 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements