

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 Questions & Answers
- Python – Elements with factors count less than K
- Program to find number of elements in A are strictly less than at least k elements in B in Python
- Two Sum Less Than K in Python
- 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
- 8085 program to count number of elements which are less than 0A
- Python program to remove Duplicates elements from a List?
- Python Program to Remove Palindromic Elements from a List
- Subarray Product Less Than K in C++
- Generate a list of Primes less than n in Python
- Maximum subarray size, such that all subarrays of that size have sum less than k in C++ program
- Python – Remove characters greater than K
- Python program to remove elements at Indices in List
- Python - Check if all the values in a list are less than a given value
- Python – Extract list with difference in extreme values greater than K
Advertisements