substracting list of tuples from another list of tuples in python

Question:

I have two lists of tuples but imagine long lists of tuples and the idea is to get these two conditions

  1. tuples that are only in list2
  2. get rid off of individul tuples where the first element of tuples in list1 match the first element tuples in list2
list1 = [(1,2), (1,3), (1,5), (3,4), (2,6)]
list2 = [(1,2), (1,3)]

expected output

result = [(3, 4), (2,6)]

I tried this approach but it results in duplicates

[x for x in list1 for y in list2 if x[1] != y[1]]

this also gets rid of (1,5) but it’s not working

[x for x in list1 if x in list2 and x[0] != list2[0]] 

this approach with duplicates

l = []
for x in list1:
    for y in list2:
        if x not in list2 and x[0] != y[0]:
            l.append(x)

[(3, 5), (3, 5), (5, 8), (5, 8)] # I want without duplicates

Answers:

Collect "first element of tuples in list1" and combine 2 conditions for a single list comprehension:

list2_x0 = [t[0] for t in list2]
res = [t for t in list1 if t in list2 or t[0] not in list2_x0]

[(1, 2), (1, 3), (3, 4), (2, 6)]
Answered By: RomanPerekhrest

If you convert your list to numpy arrays, you can solve this issue with numpy functions.

list1 = np.array([(1,2), (1,3), (1,5), (3,4), (2,6)])
list2 = np.array([(1,2), (1,3)])
todelete=np.isin(list1[:,0],list2[:,0])
difference=np.delete(list1,todelete,0)

[[3 4]
 [2 6]]
Answered By: Franciska