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 −

Example

Live Demo

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)

Output

The list is :
[(11, 14), (54, 56, 87), (98, 0, 10), (13, 76)]
The filtered tuple from the list is:
[(11, 14)]

Explanation

  • 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.

Advertisements