![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 – Remove Tuples with difference greater than K
When it is required to remove tuples with difference greater than K, use the abs() method.
Below is a demonstration of the same −
Example
my_tuple = [(41, 18), (21,57), (39, 22), (23, 42), (22, 10)] print("The tuple is :") print(my_tuple) K = 20 my_result = [element for element in my_tuple if abs(element[0] - element[1]) <= K] print("The result is :") print(my_result)
Output
The tuple is : [(41, 18), (21, 57), (39, 22), (23, 42), (22, 10)] The result is : [(39, 22), (23, 42), (22, 10)]
Explanation
A tuple is defined and displayed on the console.
The value for K is defined.
A list comprehension is used to iterate over the list, and the difference of each element of the tuple is compared with K.
This result is assigned to a variable.
This is the output that is displayed on the console.
Advertisements