Open In App

Python | Remove matching tuples

Last Updated : 08 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




# Python3 code to demonstrate
# filter repeated tuple
# using list comprehension
 
# initializing lists
test_list1 = [('Geeks', 'for'), ('Geeks', 'is'), ('Computer', 'Science')]
test_list2 = [('Geeks', 'for'), ('Geeks', 'is')]
 
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 1 : " + str(test_list2))
 
# using list comprehension
# filter repeated tuple
res =  [sub for sub in test_list1 if sub not in test_list2]
 
# print result
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




# Python3 code to demonstrate
# filter repeated tuple
# using set() + "-" operator
 
# initializing lists
test_list1 = [('Geeks', 'for'), ('Geeks', 'is'), ('Computer', 'Science')]
test_list2 = [('Geeks', 'for'), ('Geeks', 'is')]
 
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 1 : " + str(test_list2))
 
# using set() + "-" operator
# filter repeated tuple
res = list(set(test_list1) - set(test_list2))
 
# print result
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




#Python3 code to demonstrate
#filter repeated tuple
#using filter()
def filter_tuple(tup, second_list):
  return tup not in second_list
 
#initializing lists
test_list1 = [('Geeks', 'for'), ('Geeks', 'is'), ('Computer', 'Science')]
test_list2 = [('Geeks', 'for'), ('Geeks', 'is')]
 
#printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 1 : " + str(test_list2))
 
#using filter()
#filter repeated tuple
res = list(filter(lambda x: filter_tuple(x, test_list2), test_list1))
 
#print result
print("The filtered list of tuples : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy


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
 
# initializing lists
test_list1 = [('Geeks', 'for'), ('Geeks', 'is'), ('Computer', 'Science')]
test_list2 = [('Geeks', 'for'), ('Geeks', 'is')]
 
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
 
# using the custom function
res = filter_tuple_v2(test_list1, test_list2)
 
# print result
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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads