Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading