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 , co de> 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 co de> 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)) td > |
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)]