Reputation: 29
I currently have 2 "set" lists, both contain mostly the same values i.e:
a = [1,2,3,4,5,6]
b = [1,2,3,4,5,6,7,8]
What I'm trying to do is compare the two and only return 7 & 8 into another list however I'm having no luck, I've tried a few methods I've found on here such as:
c = [item for item in a if item not in b]
However I've had no luck does anyone know a quick and fairly easy method of doing this? Both lists have been "set" previously to remove any duplicates within their own lists also (just felt I should add that if that makes a difference)
Just to be clear, as I think I wasn't sorry, the example values are already in set format, in my head for some reason when you used set on a list it acted like the array_unique PHP function.
Thanks.
Upvotes: -1
Views: 160
Reputation:
You can use sets:
set(b) - set(a)
Out[65]: {7, 8}
Or more explicitly:
set(b).difference(a)
Out[67]: {7, 8}
For symmetric difference, you can use ^
. It will return elements that are in a or b, but not in both. Assume a
has an additional element, 9:
a = [1, 2, 3, 4, 5, 6, 9]
b = [1, 2, 3, 4, 5, 6, 7, 8]
set(b) ^ set(a)
Out[70]: {7, 8, 9}
Or,
set(b).symmetric_difference(a)
Out[71]: {7, 8, 9}
If they are already sets, you can just do b - a
or b ^ a
.
Your attempt does not work because there is no item in a
which is not in b
. For that difference (b-a
), you need: [item for item in b if item not in a]
.
Upvotes: 2
Reputation: 26335
Another approach is using a defaultdict
to count the number of occurrences of each element from both lists:
from collections import defaultdict
from itertools import chain
a = [1,2,3,4,5,6,9]
b = [1,2,3,4,5,6,7,8,9]
d = defaultdict(int)
for num in chain(a, b):
d[num] += 1
print([key for key, value in d.items() if value == 1])
Output:
[7, 8]
Upvotes: 0