Comparing lists

Laszlo Zsolt Nagy gandalf at designaproduct.biz
Mon Oct 10 03:45:40 EDT 2005


Odd-R. wrote:

>I have to lists, A and B, that may, or may not be equal. If they are not 
>identical, I want the output to be three new lists, X,Y and Z where X has 
>all the elements that are in A, but not in B, and Y contains all the 
>elements that are B but not in A. Z will then have the elements that are 
>in both A and B.
>  
>
These are set operations.

>One way of doing this is of course to iterate throug the lists and compare 
>each of the element, but is there a more efficient way?
>  
>
Maybe, using sets?

L1 = [1,2,3,4]
L2=[3,4,5,6]
diff1 = list(set(L1)-set(L2))           # [1,2]
diff2 = list(set(L2)-set(L1))           # [5,6]
symdiff = diff1+diff2                     # Symmetric difference [1,2,5,6]
intersect = set(L1+L2) - set(symdiff) # Intersect [3,4]

Best,

   Les




More information about the Python-list mailing list