pythonalgorithmlistsetdiscrete-mathematics

Find non-common elements in lists


I'm trying to write a piece of code that can automatically factor an expression. For example, if I have two lists [1,2,3,4] and [2,3,5], the code should be able to find the common elements in the two lists, [2,3], and combine the rest of the elements together in a new list, being [1,4,5].

From this post: How to find list intersection? I see that the common elements can be found by

set([1,2,3,4]&set([2,3,5]). 

Is there an easy way to retrieve non-common elements from each list, in my example being [1,4] and [5]?

I can go ahead and do a for loop:

lists = [[1,2,3,4],[2,3,5]]
conCommon = []
common = [2,3]
for elem in lists:
    for elem in eachList:
    if elem not in common:
        nonCommon += elem

But this seems redundant and inefficient. Does Python provide any handy function that can do that? Thanks in advance!!


Solution

  • Use the symmetric difference operator for sets (aka the XOR operator):

    >>> set([1,2,3]) ^ set([3,4,5])
    set([1, 2, 4, 5])