- Trending Categories
- Data Structure
- Operating System
- C Programming
- 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
Filter tuples according to list element presence in Python
When it is required to filter tuples based on the list element that is present, 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 of the same −
my_list = [(11, 14), (54, 56, 87), (98, 0, 10), (13, 76)] target_list = [34, 11] print("The list is : ") print(my_list) my_result = [tup for tup in my_list if any(i in tup for i in target_list)] print("The filtered tuple from the list is: ") print(my_result)
The list is : [(11, 14), (54, 56, 87), (98, 0, 10), (13, 76)] The filtered tuple from the list is: [(11, 14)]
- A list of tuple is defined, and is displayed on the console.
- Another target list is defined.
- Based on this target list, the original list of tuple is filtered out, using list comprehension.
- It is then converted to a list of tuple.
- This is assigned to a value.
- It is displayed on the console.
- Filter Tuples by Kth element from List in Python
- Python – Filter all uppercase characters from given list of tuples
- Accessing nth element from Python tuples in list
- Python – Filter Tuples with Integers
- Python – Filter unique valued tuples
- Python – Filter consecutive elements Tuples
- Find the tuples containing the given element from a list of tuples in Python
- Python program to sort a list according to the second element in sublist
- Rear element extraction from list of tuples records in Python
- Python program to sort a list according to the second element in the sublist.
- Python – Filter Tuples Product greater than K
- Combining tuples in list of tuples in Python
- Get first element with maximum value in list of tuples in Python
- Convert list of tuples to list of list in Python
- Count tuples occurrence in list of tuples in Python