- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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.
Advertisements