How to find a single element in a set that isn't in another using set comprehension

I have two sets, set1 and set2… Almost all elements in both sets are the same except for one element.

Supporting code is below:

set1 = {'dog', 'cat', 'turtle', 'monkey'}
set2 = {'dog', 'cat', 'turtle', 'gorilla'}

I am trying to get the unique element of each set into its own variable using set comprehension.

set1Unique = 'monkey'
set2Unique = 'gorilla'

I have got it working by doing the following but it is not what is required, using set comprehension is.

    set1UniqueElements = set1 - set2
    set1Unique = list(set1UniqueElements)[0]

>Solution :

The unique item is the element in the set that’s not in the other set. Hence:

>>> cat = 'cat'
>>> set1 = {'dog', cat, 'turtle', 'monkey'}
>>> set2 = {'dog', 'cat', 'turtle', 'gorilla'}
>>> {e for e in set2 if e not in set1}
{'gorilla'}
>>> {e for e in set1 if e not in set2}
{'monkey'}

To get an arbitrary element from the set (converting a single-element set to that single element on its own) you can use set.pop():

>>> {e for e in set1 if e not in set2}.pop()
'monkey'

Leave a Reply