One easy way to compare lists in python is to use Python Sets.

``` """ NOTES: - requires Python 2.4 or greater - elements of the lists must be hashable - order of the original lists is not preserved """ def unique(a): """ return the list with duplicate elements removed """ return list(set(a))```

``` def intersect(a, b): """ return the intersection of two lists """ return list(set(a) & set(b)) def union(a, b): """ return the union of two lists """ return list(set(a) | set(b)) def difference(a, b): """ show whats in list b which isn't in list a """ return list(set(b).difference(set(a))) ```

You can find differences, intersections, and unions of lists etc using sets.

Sets are not indexed.

• Thiago Marcos P. Santos
• Posted March 4, 2009 at 7:30 pm

Thanx! Help me a lot. I found that the truly difference between lists would be “symmetric_difference”.

list1 = [1, 2, 3]
list2 = [2, 3, 4]

list(set(list1).symmetric_difference(set(list2)))
[1, 4]

list(set(list1).difference(set(list2)))


• Philip Hanson
• Posted August 26, 2009 at 8:10 pm

I’m being pedantic here, but the “set difference”, i.e., the mathematical definition, is given by set.difference(). If you use set notation to describe it, here is the definition for two sets, A and B:

Python: A.difference(B)
Set notation: A – B

Python: A.symmetric_difference(B)
Set notation: (A – B) + (B – A)

It’s just semantics, really; glad you found the one you needed.

• 