Python – Extract tuples with elements in Range
Last Updated :
26 Apr, 2023
Given list of tuples, extract tuples having elements in range.
Input : test_list = [(4, 5, 7), (5, 6), (3, 8, 10 ), (4, 10)], strt, end = 5, 6 Output : [(5, 6)] Explanation : Only 1 tuple lies in range of 5-6. Input : test_list = [(4, 5, 7), (5, 6), (3, 8, 10 ), (4, 10)], strt, end = 1, 10 Output : [(4, 5, 7), (5, 6), (3, 8, 10 ), (4, 10)] Explanation : All lie in specified range.
Method #1 : Using list comprehension + all()
In this, we check for all elements in range using comparison operator and all() returns true for tuples that contain tuples in range specified.
Python3
test_list = [( 4 , 5 , 7 ), ( 5 , 6 ), ( 3 , 8 , 10 ), ( 4 , 10 )]
print ( "The original list is : " + str (test_list))
strt, end = 4 , 7
res = [sub for sub in test_list if all (ele > = strt and ele < = end for ele in sub)]
print ( "Filtered tuples : " + str (res))
|
Output
The original list is : [(4, 5, 7), (5, 6), (3, 8, 10), (4, 10)]
Filtered tuples : [(4, 5, 7), (5, 6)]
Time Complexity: O(n), where n is the length of the input list.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the list “test_list”.
Method #2 : Using filter() + lambda + all()
In this, we employ filter() to extract out tuples, according to function provided by lambda, and all() as utility to test for all elements in range tuple.
Python3
test_list = [( 4 , 5 , 7 ), ( 5 , 6 ), ( 3 , 8 , 10 ), ( 4 , 10 )]
print ( "The original list is : " + str (test_list))
strt, end = 4 , 7
res = list ( filter ( lambda sub : all (ele > = strt and ele < = end for ele in sub), test_list))
print ( "Filtered tuples : " + str (res))
|
Output
The original list is : [(4, 5, 7), (5, 6), (3, 8, 10), (4, 10)]
Filtered tuples : [(4, 5, 7), (5, 6)]
Method 3 : using a for loop
- Initialize a list of tuples test_list with some sample data.
- Define the range of values we want to extract from the tuples as strt and end.
- Create an empty list res to store the filtered tuples.
- Use a for loop to iterate through each tuple in test_list.
- Within the for loop, use the all() function to check if all elements in the current tuple are within the given range.
- If all elements are within the range, append the tuple to res.
- After the loop has finished iterating through all tuples, print the filtered tuples in res.
Python3
test_list = [( 4 , 5 , 7 ), ( 5 , 6 ), ( 3 , 8 , 10 ), ( 4 , 10 )]
strt, end = 4 , 7
res = []
for tup in test_list:
if all (strt < = ele < = end for ele in tup):
res.append(tup)
print ( "Filtered tuples : " + str (res))
|
Output
Filtered tuples : [(4, 5, 7), (5, 6)]
The time complexity of this approach is O(n*m), where n is the number of tuples in the list and m is the number of elements in each tuple.
The space complexity is O(k), where k is the number of tuples that satisfy the condition.
Share your thoughts in the comments
Please Login to comment...