0

I am currently having two lists of tuples in Python, like:

A = [(1001, 'C:\\dd\fff'), (1002, 'C:\\dd\eee')]
B = [(1001, 'C:\\dd\fff'), (1002, 'C:\\dd\eee'), (1003, 'C:\\dd\ggg')]

The resultant list should only contain values from list B which are not in list A.

Tried with (set(A) - set(B)), but due to second parameter as file path it's not providing correct result. Can someone please point out how to achieve this using Python?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
sammy
  • 1
  • `Resultant list should only contain values from list B which are not in list A.` the entire tuple? Or the first value in the tuple? – yatu Nov 04 '20 at 09:44
  • 3
    I guess what you want is `set(B) - set(A)`, note that the order of the operands matters as set difference is not conmutative – Dani Mesejo Nov 04 '20 at 09:44
  • @yatu Entire tuple – sammy Nov 04 '20 at 09:49
  • @Tomerikoo, it is similar but in my tuple it contains file names in second value of tuple, coz of which set is not getting compared. – sammy Nov 04 '20 at 09:50
  • I don't see what that has to do... tuples are hashable therefore it will work exactly the same... – Tomerikoo Nov 04 '20 at 09:51
  • Please note **the order** of subtraction... You need `set(B) - set(A)` not the other way around – Tomerikoo Nov 04 '20 at 09:52

2 Answers2

3

Please try:

list(set(B) - set(A))
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Simplecode
  • 559
  • 7
  • 19
  • @Tomerikoo this don't work , as other tuple has file path in it – sammy Nov 04 '20 at 10:11
  • @sammy I really don't understand what that means... Please edit your question with your current and expected output so we can understand what's the problem – Tomerikoo Nov 04 '20 at 10:12
0

If you do not care about order you might use set based solution, otherwise you can harness list comprehension as follows:

A = [(1001,'C:\\dd\fff'),(1002,'C:\\dd\eee')]
B = [(1001,'C:\\dd\fff'),(1002,'C:\\dd\eee'), (1003,'C:\\dd\ggg')]
result = [i for i in B if i not in A]
print(result)

Output:

[(1003, 'C:\\dd\\ggg')]
Daweo
  • 31,313
  • 3
  • 12
  • 25
  • Hi Daweo, Thanks for prompt reply, but instead of checking "i not in A" can we compare tuples first value. – sammy Nov 04 '20 at 10:00