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]
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.
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.
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:
|
operator returns elements in x
, f
or both &
operator returns elements in both x
and f
-
operator subtracts the results of &
from |
and provides us with the elements that are uniquely presented only in one of the listsIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With