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. This technique ensures that any two consecutive elements in the final list have a difference of at least K.

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]

How It Works

The algorithm follows these steps:

  • First, the list is sorted to arrange elements in ascending order

  • We iterate through consecutive pairs of elements

  • If the difference between current and next element is less than K, we remove the next element

  • Otherwise, we move to the next pair

  • This ensures minimum K difference between any two consecutive elements in the result

Alternative Approach Using List Comprehension

Here's a more concise approach using list comprehension ?

def remove_close_elements(numbers, k):
    if not numbers:
        return []
    
    sorted_list = sorted(numbers)
    result = [sorted_list[0]]
    
    for i in range(1, len(sorted_list)):
        if sorted_list[i] - result[-1] >= k:
            result.append(sorted_list[i])
    
    return result

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

print("Original list:", my_list)
filtered_list = remove_close_elements(my_list, K)
print("Filtered list:", filtered_list)
Original list: [13, 29, 24, 18, 40, 15]
Filtered list: [13, 18, 24, 29, 40]

Conclusion

Both approaches effectively remove elements with less than K difference. The while loop method modifies the list in-place, while the function approach creates a new filtered list, which is generally safer for maintaining data integrity.

Updated on: 2026-03-26T01:22:12+05:30

202 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements