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
Python – Extract tuples with elements in Range
When working with tuples in Python, you may need to extract only those tuples where all elements fall within a specific range. This can be accomplished using the filter() function combined with lambda expressions and the all() function.
Syntax
The general approach uses this pattern ?
filtered_tuples = list(filter(lambda tuple: all(start <= element <= end for element in tuple), tuple_list))
Example
Let's extract tuples where all elements are between 13 and 22 (inclusive) ?
my_list = [(13, 15, 17), (25, 56), (13, 21, 19), (44, 14)]
print("The list is:")
print(my_list)
beg, end = 13, 22
my_result = list(filter(lambda sub: all(element >= beg and element <= end for element in sub),
my_list))
print("The result is:")
print(my_result)
The list is: [(13, 15, 17), (25, 56), (13, 21, 19), (44, 14)] The result is: [(13, 15, 17), (13, 21, 19)]
How It Works
The solution breaks down into these components:
Lambda function: Creates an anonymous function that takes a tuple as input
all() function: Returns
Trueonly if all elements in the tuple satisfy the conditionGenerator expression: Checks each element against the range condition
filter() function: Applies the lambda function to each tuple and keeps only those that return
True
Alternative Approach Using List Comprehension
You can achieve the same result using list comprehension ?
my_list = [(13, 15, 17), (25, 56), (13, 21, 19), (44, 14)]
beg, end = 13, 22
# Using list comprehension
result = [tup for tup in my_list if all(beg <= element <= end for element in tup)]
print("Result using list comprehension:")
print(result)
Result using list comprehension: [(13, 15, 17), (13, 21, 19)]
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
filter() + lambda |
Functional style | Slightly faster | Functional programming approach |
| List comprehension | More Pythonic | Good performance | Most Python developers prefer this |
Conclusion
Use filter() with lambda and all() to extract tuples where all elements fall within a specified range. List comprehension offers a more readable alternative with similar functionality.
