Python Program to remove elements that are less than K difference away in a list


When it is required to remove elements that are less than K difference away in a list, a simple iteration and ‘if’ condition is used.

Example

Below is a demonstration of the same −

my_list = [13, 29, 24, 18, 40, 15]

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

K = 3

my_list = sorted(my_list)

index = 0

while index < len(my_list) - 1:
   if my_list[index] + K > my_list[index + 1]:
      del my_list[index + 1]
   else:
      index += 1

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

Output

The list is :
[13, 29, 24, 18, 40, 15]
The result is :
[13, 18, 24, 29, 40]

Explanation

  • A list is defined and displayed on the console.

  • The value for K is defined.

  • An integer is assigned to 0.

  • The list is then sorted using the ‘sorted’ function.

  • The list is iterated over, and elements which has a difference less than K are removed from the list.

  • Otherwise, the index is incremented.

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

Updated on: 08-Sep-2021

82 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements