Get only unique elements from two lists

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)