
- 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 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.
- Related Articles
- Program to find number of elements in A are strictly less than at least k elements in B in Python
- Python – Elements with factors count less than K
- Program to find list of elements which are less than limit and XOR is maximum in Python
- Python – Remove Tuples with difference greater than K
- Python program to remove Duplicates elements from a List?
- Python Program to Remove Palindromic Elements from a List
- Remove list elements larger than a specific value using Python
- Python program to remove elements at Indices in List
- Two Sum Less Than K in Python
- Python program to remove duplicate elements from a Circular Linked List
- Python – Remove characters greater than K
- Python – Extract list with difference in extreme values greater than K
- 8085 program to count number of elements which are less than 0A
- Python program to remove duplicate elements from a Doubly Linked List\n
- Generate a list of Primes less than n in Python

Advertisements