Remove matching tuples in Python


When it is required to remove the matching tuples from two list of tuples, the list comprehension can be used.

A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).

A list of tuple basically contains tuples enclosed in a list.

The list comprehension is a shorthand to iterate through the list and perform operations on it.

Below is a demonstration for the same −

Example

Live Demo

my_list_1 = [('Hi', 'there'), ('Jane', 'Hi'), ('how', 'are'), ('you', '!')]
my_list_2 = [('Hi', 'there'), ('Hi', 'Jane')]

print("The first list is : ")
print(my_list_1)
print("The second list is : ")
print(my_list_2)

my_result = [sub for sub in my_list_1 if sub not in my_list_2]

print("The filtered out list of tuples is : ")
print(my_result)

Output

The first list is :
[('Hi', 'there'), ('Jane', 'Hi'), ('how', 'are'), ('you', '!')]
The second list is :
[('Hi', 'there'), ('Hi', 'Jane')]
The filtered out list of tuples is :
[('Jane', 'Hi'), ('how', 'are'), ('you', '!')]

Explanation

  • Two list of tuples are defined, and are displayed on the console.
  • A list comprehension is used to iterate through the tuples.
  • This will filter out tuples that are present in both the list of tuples.
  • The ones left out are displayed on the console.

Updated on: 13-Mar-2021

189 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements