Method # 1: Using List Comprehension
Using List Comprehension is a brute-force technique to accomplish this task in shorthand. In this we just check each tuple and check if it contains any element from the target list.
# Python3 code to demonstrate how it works # Filter tuples by presence of a list item # use comprehension list # initialize the list of tuples test_list = [( 1 , 4 , 6 ), ( 5 , 8 ), ( 2 , code> 9 ), ( 1 , 10 )] # initialize target list tar_list = [ 6 , 10 ] # print the original list of tuples print ( " The original list: " + str (test_list) ) # Filter tuples based on the presence of a list item # using comprehension list res = [tup for tup in test_list if any ( i in tup for i in tar_list)] # print result print ( " Filtered tuple from list are: " + str (res)) |
Exit :
The original lis t: [(1, 4, 6), (5, 8), (2, 9), (1, 10)] Filtered tuple from list are: [(1, 4, 6), (1, 10)]
Method # 2: Using set ()
+ list comprehension
The above approach can be optimized by converting containers to set ()
to reduce duplicates, and perform the & amp; to retrieve the desired entries.
# Python3 code to demonstrate how it works # Filter tuples by availability list item # using set () + list comprehension # initialize the list of tuples test_list = [( 1 , 4 , 6 ), ( 5 , 8 ), ( 2 , 9 ), ( 1 , 10 )] # initialize target list tar_list = [ 6 , 10 ] # print the original list of tuples print ( "The original list:" + str (test_list)) # Filter tuples based on the presence of a list item # using set () + list comprehension < p> res = [tup for tup in test_list if ( set (tar_list) & amp; set (tup))] # print result print ( "Filtered tuple from list are:" + str (res)) |
Exit:
The original list: [(1, 4, 6), (5, 8), (2, 9), (1, 10)] Filtered tuple from list are: [( 1, 4, 6), (1, 10)]