Change language

Python | Find overlapping tuples from a list

|

Method # 1: Using a Loop
In this method, we extract overlapping pairs using conditional operators and add a suitable match in the list maintenance record.

# Python3 code to demonstrate how it works
# Find overlapping tuples from a list
# using a loop

 
# initialize the list

test_list = [( 4 , 6 ), ( 3 , 7 ), ( 7 , 10 ), ( 5 , 6 )]

 
# initialize test case

test_tup = ( 1 , 5 )

  
# print original list

print ( " The original list: " + str (test_list))

 
# Find overlapping tuples from the list
# using a loop

res = []

for tup in test_list:

if (tup [ 1 ]" = test_tup [ 0 ] and tup [ 0 ] " = test_tup [ 1 ] ):

res.append (tup)

 
# print result

print ( "The tuple elements that overlap the argument tuple is: "

  + str (res))

Output:

The original list: [(4, 6), (3, 7), (7, 10), (5, 6)]
The tuple elements that overlap the argument tuple is: [(4, 6), (3, 7), (5, 6)]

Method # 2: Using List Comprehension
This task can also be achieved using the list comprehension feature. This method is similar to the one above, just wrapped in one line for use as a shorthand.

# Python3 code to demonstrate how it works
# Find overlapping tuples from the list
# Using the comprehension list

 
# initialize the list

test_list = [( 4 , 6 ), ( 3 , 7 ), ( 7 , 10 ), ( 5 , 6 )]

 
# initialize test suite

test_tup = ( 1 , 5 )

 
# print original list

print ( "The original list:" + str (test_list))

  
# Find overlapping tuples from the list
# Using the comprehension list

res = [(idx [ 0 ], idx [ 1 ]) for idx in test_list

if idx [ 0 ]" = test_tup [ 0 ] and idx [ 0 ] " = test_tup [ 1 ]

  or idx [ 1 ]" = test_tup [ 0 ] and idx [ 1 ] " = test_tup [ 1 ]]

  
# print result

print ( " The tuple elements that overlap the argument tuple is: "

  + str (res))

Output:

The original list: [(4, 6), (3, 7), (7, 10), (5, 6)]
The tuple elements that overlap the argume nt tuple is: [(4, 6), (3, 7), (5, 6)]

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