Find non-common elements in lists


Question

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!!

1
25
5/23/2017 12:10:16 PM

Accepted Answer

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

>>> set([1,2,3]) ^ set([3,4,5])
set([1, 2, 4, 5])
48
7/5/2012 4:12:07 PM

You can use Intersection concept to deal with this kind of problems.

b1 = [1,2,3,4,5,9,11,15]
b2 = [4,5,6,7,8]
set(b1).intersection(b2)
Out[22]: {4, 5}

Best thing about using this code is it works pretty fast for large data also. I have b1 with 607139 and b2 with 296029 elements when i use this logic I get my results in 2.9 seconds.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon