Q:

Python program to filter tuples according to list element

belongs to collection: Python Tuple Programs

0

Example:

tuple = ("python", "includehelp", 43, 54.23)

Filtering tuples according to list element

We are given a list of tuples and a list consisting of integer elements. We need to create a Python program to filter tuples that contain elements that are present in the list.

Input:
[(2, 9) ,(5, 6), (1, 3), (4, 8)]
[2, 3]

Output:
[(2, 9), (1, 3)]

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Method 1:

One direct method is to use list comprehension to perform the iteration of the tuple of the list and check for the presence of elements in the list and filter based on it.

# Python program to filter tuples according 
# to list element

# Initializing and printing list 
# of tuple and filter list
tupList = [(1, 4, 6), (5, 8), (2, 9), (1, 10)]
filterList = [6, 10]

print("The elements of List of Tuple are " + str(tupList))
print("The elements of filter list are " + str(filterList))

# Filtering tuple of tuple list
filteredTupList = [tuples for tuples in tupList if any(value in tuples for value in filterList)]

print("The filter tuples from the list are " + str(filteredTupList))

Output:

The elements of List of Tuple are [(1, 4, 6), (5, 8), (2, 9), (1, 10)]
The elements of filter list are [6, 10]
The filter tuples from the list are [(1, 4, 6), (1, 10)]

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to find the maximum difference betw... >>
<< Python program to check if two lists of tuples are...