Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 828
turtlesoup Avatar asked Jul 05 '12 16:07

turtlesoup


People also ask

How do you find the uncommon element between two lists?

The most efficient and recommended method to perform this task is using the combination of set() and map() to achieve it. Firstly converting inner lists to tuples using map, and outer lists to set, use of ^ operator can perform the set symmetric difference and hence perform this task.

How do you get not common elements from two lists in Python?

You can use the . __xor__ attribute method.

How do you find common elements in a list?

Method 1:Using Set's & property Convert the lists to sets and then print set1&set2. set1&set2 returns the common elements set, where set1 is the list1 and set2 is the list2. Below is the Python3 implementation of the above approach: Python3.

How do you print unique elements from two lists in Python?

Using Python's import numpy, the unique elements in the array are also obtained. In the first step convert the list to x=numpy. array(list) and then use numpy. unique(x) function to get the unique values from the list.


1 Answers

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

>>> set([1,2,3]) ^ set([3,4,5]) set([1, 2, 4, 5]) 
like image 137
Amber Avatar answered Oct 02 '22 15:10

Amber