Python – Remove Elements in K distance with N

When it is required to remove elements which are at K distance with N, a list comprehension along with a specific condition is used. This means removing elements that fall within the range [N-K, N+K].

Understanding K Distance

An element is considered at K distance from N if the absolute difference between the element and N is less than or equal to K. In other words, elements in the range [N-K, N+K] are at K distance from N.

Elements at K Distance from N N-K (2) N (5) N+K (8) Remove this range Keep Keep

Example

Let's remove elements that are within K distance from N ?

my_list = [13, 52, 5, 45, 65, 61, 18]

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

K = 3
print("The value of K is:")
print(K)

N = 5
print("The value of N is:")
print(N)

my_result = [element for element in my_list if element < N - K or element > N + K]

print("The result is:")
print(my_result)
The list is:
[13, 52, 5, 45, 65, 61, 18]
The value of K is:
3
The value of N is:
5
The result is:
[13, 52, 45, 65, 61, 18]

How It Works

The condition element N + K keeps only elements that are:

  • Less than N-K (2): Elements like 13, 52, 45, 65, 61, 18 are not in this range

  • Greater than N+K (8): Elements like 13, 52, 45, 65, 61, 18 are not in this range

  • Element 5 is removed because it falls within [2, 8] range

Alternative Approach Using filter()

You can also use the filter() function ?

my_list = [13, 52, 5, 45, 65, 61, 18]
K = 3
N = 5

my_result = list(filter(lambda x: x < N - K or x > N + K, my_list))
print("Filtered result:", my_result)
Filtered result: [13, 52, 45, 65, 61, 18]

Conclusion

Use list comprehension with the condition element N + K to remove elements within K distance from N. This efficiently filters out elements in the range [N-K, N+K].

Updated on: 2026-03-26T01:00:43+05:30

227 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements