Python | Remove matching tuples

Python Methods and Functions

Method # 1: Using List Comprehension
This particular task can be accomplished using list comprehension as a shorthand for the for loop we would use. We simply check for the presence of one tuple in another and make the appropriate decision.

# Python3 demo code
# filter duplicate tuples
# use comprehension list

  
# initializing lists

test_list1 = [( 'Geeks' , ' for' ), ( 'Geeks' , 'is' ), ( ' Computer' , 'Science' )]

< p> test_list2 = [( 'Geeks' , ' for' ), ( 'Geeks' , ' is' )]

 
# print original lists

print ( "The original list 1:" + str (test_list1))

print ( "The original list 1:" + str (test_list2))

  
# using comprehension list
# duplicate tuple filter

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 or iginal list 1: [('Geeks',' for'), ('Geeks',' is')] The filtered list of tuples: [('Computer',' Science')] 

Method # 2. Using the set () operator + " - "
The task of getting the difference of two lists can also be done using a set that transforms the list, and then you can use the minus operator to get difference of sets.

# Python3 demo code
# duplicate tuple filter
# using the set () statement + & quot; - & quot;

 
# initializing lists

test_list1 = [( 'Geeks' , 'for' ), ( ' Geeks' , ' is' ), ( 'Computer' , 'Science' )]

test_list2 = [( 'Geeks' , ' for' ), ( 'Geeks' , 'is' )]

 
# print original lists

print ( "The original list 1:" + str (test_list1))

print ( "The original list 1:" + str (test_list2))

 
# using the set () + & quot; - & quot; statement
# duplicate tuple filter

res = list ( set (test_list1) - set (test_list2))

 
# print result

print ( "The filtered list of tuples:" + str (res))

Exit :

 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')] 




Get Solution for free from DataCamp guru