Change language

Python | Filter tuples by the presence of a list item

|

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 , 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)] 

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News


Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method