python find difference between two lists

python find difference between two lists

You can convert the lists to sets and run the usual set operations such as difference or symmetric difference. For example, set(b) - set(a) evaluates to set([7, 8, 9]).

If the second set is not always a subset of the first then the difference operator – may not always return what you expect.

E.g.

[1,2,3,4,5] - [3,4,5,6,7] = [1,2]

If you want a set of items in either list but not both lists use the symmetric difference operator ^.

[1,2,3,4,5] ^ [3,4,5,6,7] = [1,2,6,7]

The symmetric difference operator, assuming it does what you want, also has the advantage of being commutative. This means you dont need to determine in which order to compare the sets like you do with the difference operator.

http://docs.python.org/2/library/stdtypes.html#set

python find difference between two lists

Leave a Reply

Your email address will not be published.