Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python – Remove Tuples with difference greater than K
When working with tuples, you may need to filter out tuples where the absolute difference between elements exceeds a threshold value K. Python provides an efficient way to accomplish this using list comprehension and the abs() function.
Example
Here's how to remove tuples with difference greater than K ?
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)
The tuple is : [(41, 18), (21, 57), (39, 22), (23, 42), (22, 10)] The result is : [(39, 22), (23, 42), (22, 10)]
How It Works
Let's break down the filtering process ?
tuples = [(41, 18), (21, 57), (39, 22), (23, 42), (22, 10)]
K = 20
print("Checking each tuple:")
for t in tuples:
difference = abs(t[0] - t[1])
keep = difference <= K
print(f"Tuple {t}: difference = {difference}, keep = {keep}")
Checking each tuple: Tuple (41, 18): difference = 23, keep = False Tuple (21, 57): difference = 36, keep = False Tuple (39, 22): difference = 17, keep = True Tuple (23, 42): difference = 19, keep = True Tuple (22, 10): difference = 12, keep = True
Alternative Approach Using Filter
You can also use the filter() function for the same result ?
tuples = [(41, 18), (21, 57), (39, 22), (23, 42), (22, 10)]
K = 20
result = list(filter(lambda t: abs(t[0] - t[1]) <= K, tuples))
print("Filtered tuples:", result)
Filtered tuples: [(39, 22), (23, 42), (22, 10)]
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| List Comprehension | High | Fast | Simple filtering |
| Filter + Lambda | Medium | Fast | Functional programming |
Conclusion
Use list comprehension with abs() to remove tuples with difference greater than K. The abs() function ensures you get the absolute difference regardless of which element is larger.
Advertisements
