Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get only unique elements from two lists

Tags:

If I have two lists (may be with different len):

x = [1,2,3,4] f = [1,11,22,33,44,3,4]  result = [11,22,33,44] 

im doing:

for element in f:     if element in x:         f.remove(element) 

I'm getting

result = [11,22,33,44,4] 
like image 605
user3683587 Avatar asked Feb 11 '15 00:02

user3683587


People also ask

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

UPDATE:

Thanks to @Ahito:

In : list(set(x).symmetric_difference(set(f)))  Out: [33, 2, 22, 11, 44] 

This article has a neat diagram that explains what the symmetric difference does.

OLD answer:

Using this piece of Python's documentation on sets:

>>> # Demonstrate set operations on unique letters from two words ... >>> a = set('abracadabra') >>> b = set('alacazam') >>> a                                  # unique letters in a {'a', 'r', 'b', 'c', 'd'} >>> a - b                              # letters in a but not in b {'r', 'd', 'b'} >>> a | b                              # letters in a or b or both {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'} >>> a & b                              # letters in both a and b {'a', 'c'} >>> a ^ b                              # letters in a or b but not both {'r', 'd', 'b', 'm', 'z', 'l'} 

I came up with this piece of code to obtain unique elements from two lists:

(set(x) | set(f)) - (set(x) & set(f)) 

or slightly modified to return list:

list((set(x) | set(f)) - (set(x) & set(f))) #if you need a list 

Here:

  1. | operator returns elements in x, f or both
  2. & operator returns elements in both x and f
  3. - operator subtracts the results of & from | and provides us with the elements that are uniquely presented only in one of the lists
like image 56
Iopheam Avatar answered Oct 18 '22 21:10

Iopheam