
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
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.
- Related Articles
- Python – Next N elements from K value
- Delete elements with frequency atmost K in Python
- Python – Remove Tuples with difference greater than K
- Python program to replace first ‘K’ elements by ‘N’
- Python – Elements with factors count less than K
- Python – N sized substrings with K distinct characters
- Remove Tuples of Length K in Python
- Python – K middle elements
- Python Program to remove elements that are less than K difference away in a list
- Python – Filter rows with Elements as Multiple of K
- Program to find lexicographically smallest lowercase string of length k and distance n in Python
- Top K Frequent Elements in Python
- Python – Remove characters greater than K
- Place k elements such that minimum distance is maximized in C++
- Python program to remove duplicate elements from a Doubly Linked List\n

Advertisements