I am trying to find all the elements that are in list A and not in list B i.e. A-B, but I am getting the following error:

**TypeError: unsupported operand type(s) for -: 'list' and 'list'**

How can I find list difference in python?

+1 vote

Best answer

Operator '-' is not supported by list data structure, hence you are getting that error. You can compute the difference using one of the following approaches.

Approach 1: if you are concerned about the sequence of the elements and do not care about the runtime.

>>> f

[9, 11, 1, 13, 4, 5, 3, 12, 14, 10, 2, 7, 8, 6]

>>> c

[1, 2, 3]

>>> diff=[i for i in f if i not in c]

>>> diff

[9, 11, 13, 4, 5, 12, 14, 10, 7, 8, 6]

Other approaches are based on set operations, so the order of elements will not be preserved.

>>> list(set(f).difference(c))

[4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

>>> list(set(f)-set(c))

[4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

>>> list(set(f)^set(c))

[4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]