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
Remove tuples from list of tuples if greater than n in Python
When working with lists of tuples, you may need to remove tuples based on a numeric condition. This can be accomplished using list comprehension, the filter() function, or lambda expressions to check if tuple values are greater than a threshold n.
A lambda function is an anonymous function defined without a name using the lambda keyword. It takes any number of arguments but contains only a single expression, making it perfect for simple filtering operations.
Using List Comprehension
The most Pythonic way is using list comprehension to filter tuples ?
my_tuples = [('a', 130), ('b', 230), ('c', 25), ('z', 654), ('f', 69)]
n = 100
print("Original list of tuples:")
print(my_tuples)
# Keep tuples where second element is NOT greater than n
filtered_tuples = [t for t in my_tuples if t[1] <= n]
print(f"\nTuples with values <= {n}:")
print(filtered_tuples)
Original list of tuples:
[('a', 130), ('b', 230), ('c', 25), ('z', 654), ('f', 69)]
Tuples with values <= 100:
[('c', 25), ('f', 69)]
Using filter() with Lambda
The filter() function with a lambda expression provides another approach ?
my_tuples = [('a', 130), ('b', 230), ('c', 25), ('z', 654), ('f', 69)]
n = 100
print("Original list of tuples:")
print(my_tuples)
# Remove tuples where second element is greater than n
filtered_tuples = list(filter(lambda x: x[1] <= n, my_tuples))
print(f"\nAfter removing tuples with values > {n}:")
print(filtered_tuples)
Original list of tuples:
[('a', 130), ('b', 230), ('c', 25), ('z', 654), ('f', 69)]
After removing tuples with values > 100:
[('c', 25), ('f', 69)]
Using a Regular Function
For more complex conditions, you can define a separate function ?
def is_not_greater_than_n(tuple_item, threshold):
return tuple_item[1] <= threshold
my_tuples = [('a', 130), ('b', 230), ('c', 25), ('z', 654), ('f', 69)]
n = 100
print("Original list of tuples:")
print(my_tuples)
# Filter using the function
filtered_tuples = [t for t in my_tuples if is_not_greater_than_n(t, n)]
print(f"\nTuples with values not greater than {n}:")
print(filtered_tuples)
Original list of tuples:
[('a', 130), ('b', 230), ('c', 25), ('z', 654), ('f', 69)]
Tuples with values not greater than 100:
[('c', 25), ('f', 69)]
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| List Comprehension | High | Fastest | Simple conditions |
| filter() + lambda | Medium | Good | Functional programming style |
| Regular Function | High | Good | Complex conditions |
Conclusion
List comprehension is the most efficient and Pythonic way to remove tuples from a list based on numeric conditions. Use filter() with lambda for functional programming style, or regular functions for complex filtering logic.
