![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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.
Advertisements