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.

Below is a demonstration of the same −

Example

 Live Demo

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)

Output

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]

Explanation

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

  • A value for K is defined and is displayed on the console.

  • A value for N is defined and is displayed on the console.

  • A list comprehension is used to iterate over the elements and check if an element in the list is less than difference between N and K or sum of N and K.

  • If yes, the element is stored in a list.

  • This is assigned to a variable.

  • This is displayed as output on the console.

Updated on: 06-Sep-2021

92 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements