Python | Remove matching tuples
Last Updated :
08 May, 2023
The problem of removing the matching elements from two lists and constructing a new list having just the filtered elements not present in 2nd list has been discussed earlier, but sometimes, we have more than an elementary element, but a tuple as element of list. Handling such a case requires different type of handling. Lets discuss certain ways how this problem can be solved.
Method #1 : Using list comprehension This particular task can be done using the list comprehension as shorthand for the for loop which we would have used. We just check for the existence of one tuple in another and make decision accordingly.
Python3
test_list1 = [( 'Geeks' , 'for' ), ( 'Geeks' , 'is' ), ( 'Computer' , 'Science' )]
test_list2 = [( 'Geeks' , 'for' ), ( 'Geeks' , 'is' )]
print ("The original list 1 : " + str (test_list1))
print ("The original list 1 : " + str (test_list2))
res = [sub for sub in test_list1 if sub not in test_list2]
print ("The filtered list of tuples : " + str (res))
|
Output :
The original list 1 : [('Geeks', 'for'), ('Geeks', 'is'), ('Computer', 'Science')]
The original list 1 : [('Geeks', 'for'), ('Geeks', 'is')]
The filtered list of tuples : [('Computer', 'Science')]
Time Complexity: O(n*n), where n is the length of the input list. This is because we’re using the list comprehension which has a time complexity of O(n*n) in the worst case.
Auxiliary Space: O(n), as we’re using additional space res other than the input list itself with the same size of input list.
Method #2 : Using set() + “-” operator The task of getting the difference of two lists can also be done using the set that converts the list and then minus operator can be used to get the set difference.
Python3
test_list1 = [( 'Geeks' , 'for' ), ( 'Geeks' , 'is' ), ( 'Computer' , 'Science' )]
test_list2 = [( 'Geeks' , 'for' ), ( 'Geeks' , 'is' )]
print ("The original list 1 : " + str (test_list1))
print ("The original list 1 : " + str (test_list2))
res = list ( set (test_list1) - set (test_list2))
print ("The filtered list of tuples : " + str (res))
|
Output :
The original list 1 : [('Geeks', 'for'), ('Geeks', 'is'), ('Computer', 'Science')]
The original list 1 : [('Geeks', 'for'), ('Geeks', 'is')]
The filtered list of tuples : [('Computer', 'Science')]
Method #3: Using filter()
We can use the built-in filter function to filter out the matching tuples from a list. The filter function takes a function and a list as input and returns a list of elements for which the function returns True. We can define a custom function that checks if a tuple is present in the second list and use it with the filter function to get the desired result.
Python3
def filter_tuple(tup, second_list):
return tup not in second_list
test_list1 = [( 'Geeks' , 'for' ), ( 'Geeks' , 'is' ), ( 'Computer' , 'Science' )]
test_list2 = [( 'Geeks' , 'for' ), ( 'Geeks' , 'is' )]
print ( "The original list 1 : " + str (test_list1))
print ( "The original list 1 : " + str (test_list2))
res = list ( filter ( lambda x: filter_tuple(x, test_list2), test_list1))
print ( "The filtered list of tuples : " + str (res))
|
Output
The original list 1 : [('Geeks', 'for'), ('Geeks', 'is'), ('Computer', 'Science')]
The original list 1 : [('Geeks', 'for'), ('Geeks', 'is')]
The filtered list of tuples : [('Computer', 'Science')]
Time complexity: O(n^2) as it involves converting the list to a set and then using the “-” operator, which also involves looping through both lists.
Auxiliary space: O(n) as a new set is created to store the difference.
Method #4: use a for loop to iterate through each tuple in the first list and check if it is present in the second list using the “in” operator.
Step-by-step approach:
- Define a function that takes two lists as input parameters.
- Initialize an empty list to store the unique tuples.
- Use a for loop to iterate through each tuple in the first list.
- Check if the tuple is present in the second list using the “in” operator.
- If the tuple is not present, append it to the list of unique tuples.
- Return the list of unique tuples.
- Call the function with the given input lists and print the result.
Below is the implementation of the above approach:
Python3
def filter_tuple_v2(test_list1, test_list2):
unique_tuples = []
for tup in test_list1:
if tup not in test_list2:
unique_tuples.append(tup)
return unique_tuples
test_list1 = [( 'Geeks' , 'for' ), ( 'Geeks' , 'is' ), ( 'Computer' , 'Science' )]
test_list2 = [( 'Geeks' , 'for' ), ( 'Geeks' , 'is' )]
print ( "The original list 1 : " + str (test_list1))
print ( "The original list 2 : " + str (test_list2))
res = filter_tuple_v2(test_list1, test_list2)
print ( "The filtered list of tuples : " + str (res))
|
Output
The original list 1 : [('Geeks', 'for'), ('Geeks', 'is'), ('Computer', 'Science')]
The original list 2 : [('Geeks', 'for'), ('Geeks', 'is')]
The filtered list of tuples : [('Computer', 'Science')]
Time complexity: O(n^2) where n is the length of the first list.
Auxiliary space: O(n) where n is the length of the first list.
METHOD 5:Using re method
APPROACH:
This program filters out the tuples in list1 that match with any tuple in list2. It uses a regular expression pattern to match the tuples
ALGORITHM:
1. Define the lists list1 and list2.
2. Create a regular expression pattern by joining the first and second elements of each tuple in list2 with a “.*” in between.
3. Create an empty list filtered_list.
4. Loop through each tuple in list1.
5. Convert the tuple to a string and match it against the regular expression pattern using re.match().
6. If the tuple does not match with any tuple in list2, append it to the filtered_list.
7. Print the filtered_list.
Python3
import re
list1 = [( 'Geeks' , 'for' ), ( 'Geeks' , 'is' ), ( 'Computer' , 'Science' )]
list2 = [( 'Geeks' , 'for' ), ( 'Geeks' , 'is' )]
pattern1 = '|' .join([f '{x[0]}.*{x[1]}' for x in list2])
filtered_list = [t for t in list1 if not re.match(pattern1, f '{t[0]} {t[1]}' )]
print (f "The filtered list of tuples: {filtered_list}" )
|
Output
The filtered list of tuples: [('Computer', 'Science')]
Time complexity: The time complexity of this program depends on the number of tuples in list1 and list2 and the length of the tuples. In the worst case, where all tuples in list1 match with a tuple in list2, the time complexity would be O(n^2) where n is the length of the lists.
Space complexity: The space complexity of this program depends on the number of tuples in list1 and list2 and the length of the tuples. The program creates a regular expression pattern and a filtered_list, both of which take up additional memory. The space complexity would be O(n) where n is the length of the lists.
Similar Reads
Python - Remove Punctuation Tuples
Sometimes, while working with Python tuples, we can have a problem in which we need to perform the removal of all the tuples which contain punctuation in tuples. This kind of problem can occur in data filtering applications. Let's discuss certain ways in which this task can be performed. Input : tes
8 min read
Python - Remove Tuples of Length K
Given list of tuples, remove all the tuples with length K. Input : test_list = [(4, 5), (4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)], K = 2 Output : [(4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)] Explanation : (4, 5) of len = 2 is removed. Input : test_list = [(4, 5), (4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)], K =
6 min read
Python - Remove Duplicate subset Tuples
Sometimes, while working with Python tuples, we can have a problem in which we need to perform the removal of tuples, which are already present as subsets in other tuples. This kind of problem can be useful in data preprocessing. Let's discuss certain ways in which this task can be performed. Exampl
6 min read
Python - Clearing a tuple
Sometimes, while working with Records data, we can have a problem in which we may require to perform clearing of data records. Tuples, being immutable cannot be modified and hence makes this job tough. Let's discuss certain ways in which this task can be performed. Method #1 : Using list() + clear()
4 min read
Creating Sets of Tuples in Python
Tuples are an essential data structure in Python, providing a way to store ordered and immutable sequences of elements. When combined with sets, which are unordered collections of unique elements, you can create powerful and efficient data structures for various applications. In this article, we wil
3 min read
Python - Remove Kth Index Duplicates in Tuple
Sometimes, while working with Python records, we can have a problem in which we need to remove all the tuples, which have similar Kth index elements in list of records. This kind of problem is common in day-day and web development domain. Let's discuss certain ways in which this task can be performe
7 min read
Python - Remove Similar Rows from Tuple Matrix
Sometimes, while working with Tuple Matrix, we can have a problem in which we get lots of data, which are similar, i.e elements are same in rows, just the ordering of tuples is different, it's sometimes, desired to get them removed. This kind of problem can have application in domains such as web de
9 min read
Python - Remove positional rows
Given a Matrix, the task is to write a Python program to remove rows that have certain positions. Example: Input: test_list = [[3, 5, 2], [1, 8, 9], [5, 3, 1], [0, 1, 6], [9, 4, 1], [1, 2, 10], [0, 1, 2]]; idx_lis = [1, 2, 5] Output: [[3, 5, 2], [0, 1, 6], [9, 4, 1], [0, 1, 2]] Explanation: 1st, 2nd
7 min read
Python | Remove None values from list
Removing None values from a list in Python is a common task when cleaning or processing data. This process helps to filter out unwanted None elements, leaving only the meaningful values in the list for further use. There can be multiple methods to remove None values from a Python list without removi
3 min read
Python - Filter Range Length Tuples
We are given a list of tuples where each tuple contains multiple elements, and our task is to filter out tuples whose lengths do not fall within a specified range. For example, if we have a = [(1, 2), (3, 4, 5), (6,), (7, 8, 9, 10)] and the range (2, 3), we should keep only tuples with 2 or 3 elemen
3 min read