'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 1:[1]
If you are guaranteed that there is at least one element in set2 that is not in set1, and you're only looking for the first such element:
next(e for e in set2 if e not in set1)
This code stops as soon as it find any element in set2 not in set1.
Solution 2:[2]
Since there is only a single unique element, it is possible to use packing to access the elements directly:
[set1Unique] = set1 - set2
[set2Unique] = set2 - set1
Solution 3:[3]
I would use this:
ex = set1 ^ set2
set1unique = ex & set1
set2unique = ex & set2
print(set1unique)
print(set2unique)
You can can compute ex inside the setNunique formulas. It saves a line, but you compute ex twice.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Frank Yellin |
| Solution 2 | Raymond Hettinger |
| Solution 3 | lmielke |
